Connection String in Web.Config
when we use connection on page than if database server changes, than we have to make the change in the connection which requires rebuilding and deploying the application.
If there are multiple forms than we have to define connection in each page. which is time consuming and prone to errors if changes are not made every where.
So putting the connection at one place is a good idea. Using Web.config file solves our problem, we don't have to build application if connection server changes.
In the aspx file lets take a gridview
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gdvEmlpoyee" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace ADONET
{
public partial class CreatingSqlConnection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String CS= ConfigurationManager.ConnectionStrings["EmplyoeeDB"].ConnectionString;
using (SqlConnection sqlcon = new SqlConnection(CS))
{
SqlCommand sqlcmd = new SqlCommand("Select * from
EmployeeMaster", sqlcon);
sqlcon.Open();
SqlDataReader sqlreader = sqlcmd.ExecuteReader();
gdvEmlpoyee.DataSource =
sqlreader;
gdvEmlpoyee.DataBind();
sqlcon.Close();
}
}
}
}
In Web config, lets create the connection string
<configuration>
<connectionStrings>
<add name="EmplyoeeDB" connectionString="data Source=.;database=employee; integrated security=SSPI" providerName="Sql.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
Lets Execute our application we will get the following output
0 comments:
Post a Comment