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.
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 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>
I need to display data from a table in my SQL Server DB on a webpage. I've got a connection string in my Web.config file like this:
<connectionStrings>
<add name="Products.ConnectionString"
connectionString="Data Source=...."
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
In my aspx I've got a GridView with a ObjectDataSource to display the data.
In the code behind I created a method in terms of a List to return the values from my database table. However, now I was told that the users need to be able to filter the data so I created a textbox and a button to enable this but then realised in this case it would be better to have a DataTable than a List. I've always used Lists for those kind of projects though so I'm not sure how to achieve the same in a DataTable.
Here is what the code for my List looks like:
public class Products
{
public string Name { get; set;}
public int Price { get; set; }
public List<Products> DataTable()
{
List<Products> myList = new List<Products>();
string sqlQuery = "SELECT * FROM [Products_Table] ";
string connectionString = ConfigurationManager.ConnectionStrings["Products_ConnectionString"].ConnectionString; //Read connection string from config file
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(sqlQuery, con))
{
con.Open(); //Open connection
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Products t = new Products();
t.Name = reader["Name"].ToString();
t.Price = Convert.ToInt32(reader["Price"]);
myList.Add(t);
}
}
}
}
return myList;
}
}
So would be great if somebody could get me on the right track for replacing the list with a DataTable in the first place.
In your code behind you need to do something like this:
public static class ProductsDataSource
{
public static DataTable LoadProducts()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Products_ConnectionString"].ConnectionString))
using (SqlCommand command = new SqlCommand("SELECT * FROM Products_Table", conn))
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
return data;
}
}
}
Since you're using ObjectData Source make sure you're defining the SelectMethod and Typename correctly in order to return the data. Something like this:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="ProductsDataSource"
SelectMethod="LoadProducts"
/>
Something like -
GridView1.DataSource = DataTable();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
string SQL = "SELECT * FROM [Table];";
SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
I dont know of that`s what you are looking for, but this is how you bind a GridView with a DataTable.
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);
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();