Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Thursday 19 March 2015

In this article I will explain how to Read the connection string from webconfig file. We can also directly provide the connection string in code behind file. But if we write the connection string in web config file, we can use it on every page of the application. We don’t need to write the connection string again and again.

Explanation:

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

Write connection string in Webconfig File as:

       <connectionStrings>
                        <addname="con"connectionString="Data Source=mazik; Initial Catalog=Test;Integrated Security=True"/>
            </connectionStrings>

Follow these steps to read connection string in code behind file in ASP.Net (C#):

Step 1: Open code behind file and add the following namespace:

usingSystem.Data.SqlClient;
using System.Configuration;

Step 2:  Write Following code in code file:

 Code in C# to read Connection string:


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.

0 comments:

Post a Comment