Asp.net: Read the connectionstring from web.config file

In this article I am going to explain how to read the connectionstring from web.config file in asp.net application.

Implementation:

First of all set the connectionstring in web.config.

  <connectionStrings>
    <add name="con" connectionString="Data Source=vijay-pc;Initial Catalog= database;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Import the namespace

C# Code:
using System.Configuration;

VB.net Code:
Imports System.Configuration
Imports System.Data.SqlClient

Write the below given code to read ConnectionString from web.config file.

C# Code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
con.Open();

VB.net Code:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())
con.Open()





Post a Comment

0 Comments