Sunday, 11 November 2012

How to read a connection string from a web.config in asp.net

have connection string stored in web.config file, like this:

< connectionStrings >
< clear / >
< add name="SqlServerConnStr" connectionString="server=MySqlServer;Initial Catalog=MyDatabase;User ID=myUserName;Password=myPassword" providerName="System.Data.SqlClient" / >
< /connectionStrings >

To read connection string from web.config with ASP.NET server side code, you can use simple code line like this:

[ C# ]

string myConnStr = ConfigurationManager.ConnectionStrings["SqlServerConnStr"].
ConnectionString;

[ VB.NET ]

Dim myConnStr As String = _
ConfigurationManager.ConnectionStrings("SqlServerConnStr").
ConnectionString

No comments:

Post a Comment