Varad, The .NET Guy!

Exploring the excitement of Microsoft .NET and much more..

ASP.NET 2.0, Using Connection Strings from web.config

ASP.NET v2.0 has a couple new ways to reference connection strings stored in the web.config or machine.config file.

A typical web.config file in v2.0 could have the following section which is placed directly under the root <configuration> section.

<connectionStrings>
    <
remove name="LocalSqlServer"
/>
    <
add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"
/>
    <add name="MainConnStr" 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 code using:

[C#]
string connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;

[VB]
Dim connStr As String = ConfigurationManager.ConnectionStrings("MainConnStr").ConnectionString

Note that the namespace for this is System.Configuration so for a console application the full namespace is required.

Or 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]"
/>

[via owscott]

Posted: Aug 28 2005, 08:58 AM by Varad | with 2 comment(s)
Filed under:

Comments

Mischa Kroon said:

Nice shortcut :)
# August 29, 2005 10:02 AM

Eric Newton said:

how about (like appsettings' file attribute) allowing for local config changes without having to "fix" the config file with every deployment?
# August 29, 2005 10:49 AM