Professional Windows hosting from ORCS Web
    
An Unrivaled Windows Hosting Experience    
1-888-313-9421  |  webteam@orcsweb.com        
From Our Clients:
"I know I have told you a thousand times, but your service is top-notch, I love bringing clients your way, and I look forward to working with you on future projects."

Join our community of clients at: 1-888-313-9421

Using Connection Strings from Web.config in ASP.NET v2.0
By Scott Forsyth
August 26, 2005

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>

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

Scott Forsyth is the Director of IT at ORCS Web, Inc. - a company that provides managed hosting solutions for clients who develop and deploy their applications on Microsoft Windows platforms. Services include shared hosting, dedicated hosting, and webfarm hosting, with specialty in .Net, SQL Server, and architecting highly scalable solutions.

Copyright © 1996-2010 ORCS Web, Inc. All rights reserved.