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>
Related
I'm unable to insert data into table. we are using local db. I'm not even getting any exception
string constr = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("insert into Client_Name(Name) values('" + textBox1.Text + "')",con);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
Console.Write("Exception");
}
}
In app.config
<connectionStrings>
<add name="server" connectionString="Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Integrated
Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
I have tried all the possible way, and got the best solution considering your scenario.
During an hour observation got to know due database connection
persistence issue you were having that problem try below snippet would
work as expected.
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Connect Timeout=30;Integrated Security=True;";
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("Insert into [LocalTestTable] values (#name,#description)", _connection))
{
command.Parameters.AddWithValue("#name", "TestFlatName");
command.Parameters.AddWithValue("#description", "TestFlatDescription");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Hope that will resolve your problem without having anymore issue.
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>
I have a problem with displaying data from a column that is in SQL Server, to insert as x and y in my chart in asp.net the problem is this, so it seems the method (DataBindTable) is waiting for IEnumerable But my SqlDataReader does not implement IEnumerable. If you could give me examples of how to overcome this difficulty, thank you.
Here is the insertion code:
protected void Chart1_Load13(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT [Consumo_Medio_Real], [Tipo_de_Fatura] FROM [dbo].[t_faturas]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
Chart1.DataBindTable(rdr,"Consumo_Medio_Real");
}
}
This is the connection code:
<connectionStrings>
<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>
You could load your datareader into a data table:
DataTable dt = new DataTable();
SqlDataReader rdr = cmd.ExecuteReader();
dt.Load(rdr);
dataReader.Close();
Chart1.DataBindTable(dt,"Consumo_Medio_Real");
Try with this:
string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT [Consumo_Medio_Real], [Tipo_de_Fatura] FROM [dbo].[t_faturas]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
//Add datatable...
System.Data.DataTable dt = new DataTable();
dt.Load(rdr);
var enumerableTable = (dt as System.ComponentModel.IListSource).GetList();
chart1.DataBindTable(enumerableTable , "X");
here you have an answer...
Hope this help.
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);
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.