Read connection string from web.config file

This example shows you how to read connection string from asp.net web.config file.

Define connection string in web.config

<connectionStrings> <add name="myCon" connectionString="Data Source=ServerDetails;user id=sa;password=xxxxxx;database=DbName;" providerName="System.Data.SqlClient"/> </connectionStrings>

Accessing/Reading connection string from c# code
Add reference -> using System.Configuration;

SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;