how not to hard code connection stringin all pages

I have a webconfig file which has a connectionstring in it...

But then when ever i access a database i have to write the same connectionstring again and again... is there a way it can take the value of the connectionstring from the webconfig file itself..????

System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
            dataConnection.ConnectionString =
                @"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";

            System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
            dataCommand.Connection = dataConnection;

any suggestions??

13.10.2009 21:50:17
3 ОТВЕТА
РЕШЕНИЕ

Try this:

string strConnString = 
ConfigurationManager.ConnectionStrings["NameOfConnectionString"].ConnectionString;

EDIT: Your code would now look something like this:

System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
            dataConnection.ConnectionString =
                ConfigurationManager.ConnectionStrings["NameOfConnectionString"].ConnectionString;

            System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
            dataCommand.Connection = dataConnection;

Just remember to replace NameOfConnectionString with the actual name of your connection string, and add a reference to System.Configuration (thanks NissanFan!)

6
13.10.2009 22:02:16
Make sure you add a reference to System.Configuration before you do this.
Keith Adler 13.10.2009 21:53:37
And make sure to place your updated (since its not used, can be outdated) connection string inside /configuration/connectionStrings hive, in your web.config
Rubens Farias 13.10.2009 21:57:44
so in this im hard coding Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True in place of NameofConnectionstring???
user175084 13.10.2009 21:58:17
so whats the difference between what i wrote in my code and what u have written... by doing this i still am writing the entireconnectionstring on each page,,,,
user175084 13.10.2009 22:07:42
No, the webconfig gets a line in the connectionstrings section associating "NameOfConnectionString" to "Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True" so that you don't have the hardcoded value all over the place.
JB King 13.10.2009 22:07:53

In .NET there is a standard object named My.Settings that automatically refers to all your settings in the webconfig file.

You refer to values there as My.Settings.Item("settingName")

0
27.09.2011 16:14:16

How to: Read Connection Strings from the Web.config File

http://msdn.microsoft.com/en-us/library/ms178411.aspx

1
13.10.2009 22:02:55