Creating a StudentDB Class for ASP.NET 2.0 - Storing the Connection String in a Web.Config file
(Page 4 of 5 )
New in ASP.NET 2.0 is the <connectionStrings> element, or we could say section, in the web.config file. You can add connection strings as child elements to the <connectionStrings> element as in the following code:
<connectionStrings>
<add name="SchoolConnectionString"
connectionString="Data Source=(local);Initial
Catalog=School;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
You need to put this <connectionStrings> element in the Web.Config file of the website. To do that, right click on the website in Solution Explorer; right click then select Add New Item, select Web Configuration File and leave its default name as shown in the following screenshot:

Click on add; now open the Web.Config file and locate the element <connectionStrings /> and replace it with the one above. Note that we have used the child element <add> in order to add a connection string to the Web.Config. The name attribute denotes the name that will be used in code to refer to that particular connection string. The connection string itself is added using the connectionString attribute.
Please, if you are not familiar with ADO.NET, you must read about it before you proceed. I have written many articles about ADO.NET objects covering SqlConnection, SqlCommand and SqlDataReader. These will give you an understanding of how to work with ADO.NET.
To retrieve the connection string from the C# code you need the following line of code:
WebConfigurationManager.ConnectionStrings
["SchoolConnectionString"].ConnectionString;
The WebConfigurationManager class has a property called ConnectionStrings that is used to retrieve the connection string from the configuration file. This property is of type ConnectionStringSettingsCollection so we use the indexer syntax to access its individual objects which are of type ConnectionStringSettings. We get the connection string itself through the use of the ConnectionStringSettings.ConnectionString property. This article is not about configuring ASP.NET applications so I will not spend the time to talk about the Web.Config file; please consult other articles on this topic. We will write the above line in the StudentDB C# class in the next section.
Next: The StudentDB class >>
More ASP.NET Articles
More By Michael Youssef