If I have a connection string defined in my web.config file, how do I create a connection to the SQL db from C# code (sorry forgot to specify) and then call a stored procedure. I would then like to eventually use this data in some way as my DataSource for a GridView.
Here is how the connection string is defined in the web.config:
<connectionStrings>
<add name="db.Name" connectionString="Data Source=db;Initial Catalog=dbCat;User ID=userId;Password=userPass;" providerName="System.Data.SqlClient" />
</connectionStrings>
The db server is a Microsoft SQL server.
Here is what I was looking for:
ConnectionStringSettings conSet = ConfigurationManager.ConnectionStrings["db.Name"];
SqlConnection con = new SqlConnection(conSet.ConnectionString);
The code to get the data is fairly trivial. I was more interested in accessing it from a connectionString variable in the web.config file.
Best Answer
If it's a resource file like so:
private static readonly string connString = Resource1.connString;
Where connString is the name of the key. If it is a
web.config
fileSomething like so:
private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"];
where conn is defined in your web config file.Then call the sproc:
That's if you are coding in C#, VB.net its the same deal just a bit more wordier :), here's a small sample:
Of course you should use a
using
statement instead oftry/catch/finally
to ensure you clean up your resources that are being used.