can´t fill my chart using data set - c#

I'm having a problem passing the data I retrive from my database in sql server to be used to fill my graph.
It turns out that the error says that the type of data that I am inserting is not correct:
Error: Serial data points are not values ​​of type System.Data.DataViewManagerListItemTypeDescriptor
Can you help me create a way to convert this data to fill my graph?
My code:
protected void Chart1_Load18(object sender, EventArgs e)
{
string cs1 = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(cs1))
{
var da = new SqlDataAdapter("USE [DB_SACC] SELECT [Consumo_Medio_Real] FROM [dbo].[t_faturas]", con1);
con1.Open();
DataSet ds = new DataSet();
da.Fill(ds);
var enumerableTable1 = (ds as System.ComponentModel.IListSource).GetList();
Chart1.Series["Consumo Médio Real"].Points.DataBind(enumerableTable1, "Consumo_Medio_Real", "", "");
ds.Clear();
con1.Close();
My connection:
<connectionStrings>
<add name="CS1" connectionString="Data Source=ASUS;Initial Catalog=DB_SACC;Persist Security Info=True;User ID=sa;Password=1234"
providerName="System.Data.SqlClient" />
</connectionStrings>

Related

Gridview table not being displayed in asp.net webform

I just want to display the gridview with some specific queries.
I've tried doing it below.
This code shows "No data matches" when wrong parameter is passed in query ,but displays nothing even when parameters are correct.
I am new to asp.net .Please tell me,what important line ,I'm missing
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Filter"] = "ALL";
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
string query = "SELECT ContactName, City, Country, PostalCode FROM Customers";
SqlCommand cmd = new SqlCommand("SELECT ContactName, City, Country, PostalCode FROM Customers WHERE Country='UK'" );
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
The code is working and returning 7 rows from northwind database into the gridview.
Your connection string should be like this in web.config file:
<connectionStrings>
<add name="NorthwindConnectionString1" connectionString="server=.; database=northwnd; integrated security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>

Is it possible to use the DataBindTable to define values two X?

I am developing a relatively simple code that allows you to make a select to my database to extract the values ​​of two columns wanted to be both of X.
My problem using the DataBindTable method is not allowing me to define the second X.
Here is the code for the first X (the one that works):
protected void Chart1_Load16(object sender, EventArgs e)
{
string cs1 = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(cs1))
{
SqlCommand cmd1 = new SqlCommand("SELECT [Consumo_Medio_Real] FROM [dbo].[t_faturas]", con1);
con1.Open();
SqlDataReader rdr1 = cmd1.ExecuteReader();
var dt1 = new System.Data.DataTable();
dt1.Load(rdr1);
var enumerableTable1 = (dt1 as System.ComponentModel.IListSource).GetList();
Chart1.DataBindTable(enumerableTable1, "Consumo_Medio_Real");
And this is the code for the second (doesn´t work):
string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT [Consumo_Mes_Anterior] FROM [dbo].[t_leituras]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
var dt = new System.Data.DataTable();
dt.Load(rdr);
var enumerableTable = (dt as System.ComponentModel.IListSource).GetList();
Chart1.DataBindTable(enumerableTable, "Consumo_Mes_Anterior");
Connections:
<connectionStrings>
<add name="CS1" connectionString="Data Source=ASUS;Initial Catalog=DB_SACC;Persist Security Info=True;User ID=sa;Password=1234"
providerName="System.Data.SqlClient" />
<add name="CS" connectionString="Data Source=ASUS;Initial Catalog=DB_SACC;Persist Security Info=True;User ID=sa;Password=1234"
providerName="System.Data.SqlClient" />
</connectionStrings>

Barcharts in C#

Here I created a barchart using a Windows application with C#. I retrieve the data from stored procedure and bind the with barchart. So far I wrote this code:
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=ARUN-PC/SQLEXPRESS;Initial Catalog=InsightPro_Latest ;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SumofPowders";
DataSet ds = new DataSet();
da.Fill(ds);
InsightPro_BarChart.DataSource = ds;
InsightPro_BarChart.DataBind();
con.Close();
}
catch
{
}
Now I faced the error: The ConnectionString property has not been initialized. I don't know where I did the mistake.
Can anyone please clarify my doubt in coding also? Thanks in advance.
Provide connection string to SqlConnection (otherwise it will not know which database connect to):
string connectionString = "Server=Name;Database=DbName;User=Foo;Password=Bar";
SqlConnection con = new SqlConnection(connectionString);
// you can also set connection string via property
// con.ConnectionString = connectionString;
Usually connection strings are stored in configuration file of your application in <connectionStrings> section (see Connection Strings and Configuration Files):
<connectionStrings>
<add name="myConnection"
connectionString="Server=Name;Database=DbName;User=Foo;Password=Bar"
providerName="System.Data.SqlClient"/>
</connectionStrings>
You can use ConfigurationManager to get connection string from config file (you should add reference to System.Configuration assembly):
string connectionString =
ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
You need add the connection string to you SQL.
For example:
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;";
Then do the needed SqlConnection as:
SqlConnection con = new SqlConnection(connectionString);
More on Connection strings: http://www.connectionstrings.com/sql-server-2005/
You can add your database connection details in the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Once you have the configuration, you then need to access the same for your connection.
You can use ConfigurationManager:
using System;
using System.Configuration;
var connectionString = ConfigurationManager.ConnectionStrings["Test"];
Then use the SqlConnection to pass the connection and start off:
SqlConnection con = new SqlConnection(connectionString);
Try this
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword";
conn.Open();
Web.config
<connectionStrings>
<add name="ApplicationServices" connectionString="copy connection string here"
/>
</connectionStrings>
SqlCommand command = new SqlCommand();
command.CommandText = "SumofPowders";
command.CommandType = CommandType.StoredProcedure;
con.open();
SqlDataAdapter da = new SqlDataAdapter(command,con);
DataSet ds = new DataSet();
da.Fill(ds);
InsightPro_BarChart.DataSource = ds;
InsightPro_BarChart.DataBind();
add a connection string to your webconfig inside ConnectionString tag
<add name="constr" connectionString="Data Source=ARUN-PC/SQLEXPRESS;Initial Catalog=InsightPro_Latest ;User ID= YourServersername ;Password=YourServerPassword" providerName="System.Data.SqlClient"/>
in your code behind
string conn = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(conn);

Solve the error "The ConnectionString property has not been initialized."?

My code is view all the data in the gridview
Web.config code is
<configuration>
<connectionStrings>
<add name="ConStr" connectionString="DataSource=.;Integrated Security=SSPI;Initial catalog=sshopping"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>
It is coded in external class
namespace DBAction
{
public class ViewAction
{
public DataSet GetAllData()
{
SqlCommand cmd = DataConnection.GetConnection().CreateCommand();
cmd.CommandText = "Select UserName,Password,RoleName,EmailID,SecurityQuestion,SecurityAnswer,LastLogin from LoginInfo";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Dispose();
DataConnection.CloseConnection();
return ds;
}
}
}
it is giving error in line da.Fill(ds)
The code to bind data source with gridview is coded on page load like this.
DataSet ds = new ViewAction().GetAllData();
gvLoginInfo.DataSource = ds;
gvLoginInfo.DataBind();
And conectionstring code in data connection class is
public static SqlConnection GetConnection()
{
if (con == null)
{
con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
con.Open();
}
return con;
}
And one one error is
Exception Details: System.ArgumentException: Keyword not supported: 'datasource'.
Source Error:
Line 19: {
Line 20: con = new SqlConnection();
Line 21: con.ConnectionString =ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
Line 22: con.Open();
Line 23: }
The error is in the Web.Config only. Please put one space between DataSource in connectionString as: Data Source. Thus your connection String will become:
"Data Source=.;Integrated Security=SSPI;Initial catalog=sshopping".
From the examples i see online, in your connection string replace "DataSource" with "Data Source" (with a space between the two words).
http://msdn.microsoft.com/en-us/library/ms156450.aspx
I was getting same error, even after made all changes you mentioned above.
And after that, I change my code in that way:
My Web.Config:
<connectionStrings>
<add name="conStr" connectionString="Data Source=SomeDS;Initial Catalog=SomeCatalog;User Id=myId;Password=myPass" />
</connectionStrings>
My old Code:
string ConnectionString = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (var sqlConnection = new SqlConnection(ConnectionString ))
{
var result= sqlConnection.Query<My_Class>("MY_PROC_NAME", new { count }, commandType: CommandType.StoredProcedure);
return result;
}
My newCode:
var dt = new DataTable();
using (var cnn = new SqlConnection(ConnectionString ))
using (var cmd = new SqlCommand("MY_PROC_NAME", cnn))
{
cmd.CommandType = CommandType.StoredProcedure;
cnn.Open();
var sqlReader = cmd.ExecuteReader();
if (sqlReader.HasRows)
dt.Load(sqlReader);
cnn.Close();
}
result = dt.DataTableToList<My_Class>();
DataTableToList is a converter method, if you need i can share it, too.

data binding for gridview

I'm trying to bind my sql table with the grid view using the following code:
string connectionString = WebConfigurationManager.ConnectionStrings["Gen_Lic"].ConnectionString; //<-- error
string selectSQL = "SELECT * FROM Gen_Lic";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Gen_Lic");
Gen_Lic_Grid.DataSource = ds;
Gen_Lic_Grid.DataBind();
But I don't know where I'm going wrong with this, but I'm getting an error:
Object reference not set to an instance of an object.
Any suggestions?
This is my web.config file:
<connectionStrings>
<add name="Gen_LicConnectionString" connectionString="Data Source=ESHA\SQLEXPRESS;Initial Catalog=Gen_Lic;User ID=sa;Password=sa#" providerName="System.Data.SqlClient" />
</connectionStrings>
Use this link to add connection string in web config.
http://www.aspdotnet-suresh.com/2011/11/write-connection-strings-in-webconfig.html
you were using a different name in the call and webconfig.
string connectionString = ConfigurationManager.ConnectionStrings["Gen_LicConnectionString"].ConnectionString;
You didn't open SqlConnection. you have to Open Connection before creating a command variable.
string connectionString = WebConfigurationManager.ConnectionStrings["Gen_Lic"].ConnectionString; //<-- error
string selectSQL = "SELECT * FROM Gen_Lic";
SqlConnection con = new SqlConnection(connectionString);
con.Open();// Need to Open Connection before to Create SQL Comamnd
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Gen_Lic");
Gen_Lic_Grid.DataSource = ds;
Gen_Lic_Grid.DataBind();
Always check your connection string and set the connection to open.
to make it safe, set always your connection to close.
if(connection.State == ConnectionState.Open)
connection.Close();
connection.Open();

Categories

Resources