Home Gitesh Portfolio Blog About Me Gallery Contact

Read/Get a SQL connection string from the web.config file C# dynamically

Example of a Connection String

<connectionStrings>
<add name="CMSConnectionString" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true"providerName="System.Data.SqlClient"/>
</connectionStrings>

You can reference this directly from codebehind using:[C#]

string ConnectionStringFromWebConfig= ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString;
stringsqlConnectString = @"" + ConnectionStringFromWebConfig + "";
SqlConnectionsqlConnection = newSqlConnection(sqlConnectString);

Namespace required

usingSystem.Configuration; 

 For ascx or aspx file

You can reference this declaratively within the ConnectionString property of a SqlDataSource:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
  ConnectionString="<%$ ConnectionStrings:MainConnStr %>"
  SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]" />


Posted: 20/04/2013 11:43:38 p.m. by Gitesh Shah | with 0 comments