开发者

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;Integ开发者_JS百科rated Security=True";

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

any suggestions??


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


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

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜