Friday, May 3, 2013

How to Read Connection String from Web.config file

1 comment

This article on connection string will focus on accessing connection string from web.configfile in code behind file of asp.net web forms.
The sample code is written using visual studio 2012 and given in both C# and VB.NET languages.

First of all create connection string in web.config file.

Sample code of web.config file having connection string is given below:
<configuration>
<connectionStrings> 
<addname="con"connectionString="Data Source=ACER-PC;Initial Catalog=Student;Integrated Security=True"/>
</connectionStrings>
<system.web>
<compilationdebug="false"targetFramework="4.5"/>
<httpRuntimetargetFramework="4.5"/>
</system.web> 
</configuration>

Replace Data Source value according to your system setting.

Follow these steps to read connection string in code behind file:

Step 1: Open code behind file and add the following namespace:
usingSystem.Data.SqlClient;
using System.Configuration;
Step 2:  Now add the following code in code file:

 Code in C#:
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{    protected void Page_Load(object sender, EventArgs e)
    {
      SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
        con.Open();
    }
}

Code in VB.NET:
Imports System.Data.SqlClient
Imports System.Configuration
Partial Class Default2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())
        con.Open()
    End Sub
End Class

Here ‘con ‘is the name of Connection String in web.config file.

1 comment:

  1. nice explanation. Worked great for me. Thank you for posting it!

    ReplyDelete