June 30, 2011 06:42 by
Scott
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]" />