How to get Connection String from Web.Config in Asp.Net C#

In this tutorial we have learn How to get Connection String from Web.Config in Asp.Net C#,when you design a big software you should set the connection string for once and use it in many forms. In this method you use the name of the Connection String instead of the connection string text.

Every time you want to change the connection string just change the main connection string in the web.Config file.

By this method you don’t need to change all of the forms in your project, just change the Connection String in the web.Config.

In web.config

First of all you should set the connection string in the web.Config file. For example I set the connection string for my database as you see here

<configuration>

<system.web>
<compilation debug=”true” targetFramework=”4.0″ />
</system.web>

<connectionStrings>
<add name=”constr” connectionString=”Data Source=HOME-PC; Initial Catalog=YourDatabaseName;Integrated Security=True;” providerName=”system.data.sqlclient” />
</connectionStrings>

</configuration>

In your forms you set references that you want to use:

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

Then you can get the Connection String from the App.Config by using the ConnectionStrings property.