Thursday, December 22, 2011

How To - Get connection string from web.config in ASP.NET

Sample web.config



  
  


Get Connection string at runtime

In order to retrieve a specific connection string from the web.config, first we need a reference to System.Configuration. In .NET 4, the reference has already been added for us, but we still need to add "using System.Configuration;" in our page. In previous .NET versions, you needed to add the reference manually by going to the references folder in the solution explorer, right click and select Add Reference. From the .NET tab, select System.Configuration. After having done the above, we can get the connection string required by using the following code.
private const string CONNECTIONSTRING_NAME = "LocalSqlServer";
string myConnectionString = ConfigurationManager.ConnectionStrings[CONNECTIONSTRING_NAME].ConnectionString;

Using connection string expression syntax

We can bind the connection string directly to the connection string property of the sqldatasource using ASP.NET expressions. This is done by using the following syntax




No comments:

Post a Comment