Read connectionString from web.config

It is a good practice to store the connection string for your application in a config file rather than as a hard coded string in your code. It becomes much easier for you later on when you may want to change the connectionString.

How to add a connectionString to a Web.config file ?

Under the connectionString node, add a  name and a connectionString. Here name represent your connection string, source will be your computer name, Initial catalog will be your database name, and finally id and pasword will be your database server name and password.

WEB.CONFIG

{code type=html}

<connectionStrings>

<add
name=”localConn”
connectionString=”Data Source=YASSER-VAIO;Initial Catalog=ssc;
Persist Security Info=True;
User ID=sa;
Password=shaikh”
providerName=”System.Data.SqlClient”/>

</connectionStrings>

{/code}

SOMEPAGE.ASPX.CS

We can use the ConfigurationManager class present in System.Configuration namespace to get a specific connectionStrings from the web.config file. You will simply need to provide the name of the connectionString(‘localConn‘) as shown in the example below.

{code type=javascript}

private string GetConnectionString()
{

var conString = ConfigurationManager.ConnectionStrings[“localConn”];

if(conString == null)
{
throw new Exception(“Connection String is not defined! Please check your Web.config”);
}

return conString.ConnectionString;

}

{/code}

Happy Coding !! :)