<%@ Page %>

Storing Database Connection String In Web.config


Many times our application requires certain things like connection string, application wide parameters to be stored external to the application. The traditional way to do this was INI files or registry entries. However, when you are talking about web application both of the possibilities are tedious as they have problems of their own. ASP.NET provides a cool way to do that. You can store such values in web.config file in the <appSettings> section. Following code illustrates this.

Storing values in web.config

Add following markup in your web.config file:
    <add key="connectionstring" 
    value="Integrated Security=SSPI;
    Initial Catalog=Northwind;
    Data Source=MyServer\NetSDK" />

Namespaces Required

Following namespaces provide classes required for our operation:

VB.NET Code to retrieve values

Following code shows how to retrieve the values using VB.NET:
Dim myvar As String
Dim nv As NameValueCollection
nv = ConfigurationSettings.AppSettings()
myvar = nv("connectionstring")
You can quickly retrieve single setting as follows:
 Dim myvar As String 

C# Code to retrieve values

Following code shows how to retrieve the values using C#:
string myvar;
NameValueCollection nv;
You can quickly retrieve single setting as follows:
string myvar;
I hope you found the examples useful.

Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a yoga mentor, meditation teacher, and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his private online courses on ASP.NET and meditation go here and here.

Posted On : 08 June 2002

Tags : ASP.NET Data Access Configuration Administration