views:

100

answers:

3

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??

+6  A: 

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!)

Matthew Jones
Make sure you add a reference to System.Configuration before you do this.
Nissan Fan
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
so in this im hard coding Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True in place of NameofConnectionstring???
so the above code is stored in webconfig???
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,,,,
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
got it.... thanks all
A: 

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")

Ron

Ron Savage
+1  A: 

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

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

x0n