Connection String In Web.Config file

Posted by Chvrsri under C# category on | Points: 40 | Views : 4024
Generally in web based applications for getting the connection from the database we create an object relating to the particular database for example we will do some thing like :

using System.Data.SqlClient
SqlConnection con=new SqlConnection("Connection String");

But its not a good practice if we could write the connection string in the Web.Config file it gives Code Feasability.For Example if we want to deploy our project into test server we need not open and close all the time just access that connection string purpose will be solved. Here i will explain a small example relating to that :

In Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
string query = "SELECT ProductID, ProductName, UnitPrice FROM muldel";
SqlDataAdapter da = new SqlDataAdapter(query, connectionString);
DataTable table = new DataTable();
GridView1.DataSource = table;

Now the Design page Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
<title>Untitled Page</title>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server">


Now comes our Web.Config file

<?xml version="1.0"?>
<add key="ConnectionString" value="server=user-182;uid=sa;pwd=007;database=srikanthch"/>
<compilation debug="true"/>

This is a simple example which illustrates the use of accessing a Database Connection String from the Configuration file.

Cheers !! Happy Coding !!!

Comments or Responses

Posted by: Akiii on: 6/4/2011 Level:Bronze | Status: [Member] | Points: 10

can we write like this in the web.config file....


<add name="TestConnectionString1" connectionString="Data Source=server name;Initial Catalog=DatabaseName;User ID=Username;Password=Password " providerName="System.Data.SqlClient"/>
<compilation debug="true" targetFramework="4.0"/>

Please let me know what is the difference between your code and this code ....?

Thanks and Regards

Login to post response