ASP.NET EXAMPLE : Read or Write connection strings from web.config file using asp.net

In this article I am going to explain how to read or write connection strings in web.config file using asp.net .

In this example i will show you how to write connection string in a Web.config file and also i will show you how to read that connection string from  Web.config file .



Write connection strings in web.config file

We write connection string inside connectionStrings element.The connectionStrings element is a direct child of the <configuration> element and a peer of the system.web element.


<connectionStrings>
            <add
              name="MyConString"
              connectionString="Data Source=serverName;Initial
    Catalog=YourDataBasename;Persist Security Info=True;User
    ID=dbuserName;Password=dbpassword"
              providerName="System.Data.SqlClient"
  />
      </connectionStrings>


Read connection strings from web.config file

After adding connectionString we need to write the some code in our codebehind file to get connection string from web.config.Below is code which we have to write to read connectionString from web.config file.


C# CODE



using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class dbString  : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{  
//the below line will read ConnectionStrings from web.config file.
string dbstrcon = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
//the below line will create new sqlconnection and connection to database by using connection string from web.config file.
SqlConnection mycon = new SqlConnection(dbstrcon);
mycon.Open();
}
}


Tags: ,

Join Us!