Connection Strings In Web.config File Using ASP.NET

After opening the web.config file in application, add sample db connection in connectionStrings section like this: 

    <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />   

Declaring connectionStrings in web.config file:

    <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient" />   

There is no need of username and password to access the database server.

Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.

using System.Configuration;

This namespace is used to get configuration section details from web.config file.

C# code

using System;  
using System.Data.SqlClient;  
using System.Configuration;  
public partial class _Default: System.Web.UI.Page {  
    protected void Page_Load(object sender, EventArgs e) {  
        //Get connection string from web.config file  
        string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
        //create new sqlconnection and connection to database by using connection string from web.config file  
        SqlConnection con = new SqlConnection(strcon);