Learn ASP.NET Core 3.1 with mini project : MVC, Razor Pages, Web API, Entity Framework Core, and Blazor. Hands-on online training course starting in June 2020. Click here to know more.

<%@ Page %>

Storing Database Connection String In Web.config

Introduction

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:
<configuration>
    <appSettings>
    <add key="connectionstring" 
    value="Integrated Security=SSPI;
    Initial Catalog=Northwind;
    Data Source=MyServer\NetSDK" />
    </appSettings>

Namespaces Required

Following namespaces provide classes required for our operation:
System.Collections.Specialized
System.Configuration

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 
 myvar=ConfigurationSettings.AppSettings("connectionstring")

C# Code to retrieve values

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

Bipin Joshi is an independent software consultant, trainer, author, yoga mentor, and meditation teacher. He has been programming, meditating, and teaching for 24+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Facebook  Twitter  LinkedIn  YouTube

Posted On : 08 June 2002


Tags : ASP.NET Data Access Configuration Administration


Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.

  

Receive Weekly Updates