Monday, August 26, 2013

Filled Under:
, ,

Create Connection String in Asp.net using web.config file

Hello Friends,

Today I am writing this post because of I found out that beginners got a problem to create connection with database in web config file in asp.net. So, Solution is here. Enjoy it.....

Web Config File

<configuration>

  <connectionStrings>

    <add name="nameofConnection" connectionString="Data Source=servername; Initial Catalog=DatabaseName; User ID=UserName; Password=Password;"/>

  </connectionStrings>

  <system.web>
    <compilation debug="false" targetFramework="4.0" />
  </system.web>

</configuration>


Default.aspx

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title>Connection String Demo</title>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView runat="server" ID="GridView1">
        </asp:GridView>
    </div>
    </form>
</body>
</html>



Default.aspx.cs

Add System.Configuration and System.Data.SqlClient namespace to add connection with sql.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)

   {

string connectionString = ConfigurationManager.ConnectionStrings["nameofConnection"].ConnectionString;

string query = "SELECT ProductID, ProductName, UnitPrice FROM tblProduct";
       
SqlDataAdapter da = new SqlDataAdapter(query, connectionString);

DataTable table = new DataTable();

da.Fill(table);

GridView1.DataSource = table;

GridView1.DataBind();

   }
}

If you like this post share it.. If you encounter any problems, feel free and comment below to find solution. Share Your Experience with us.












0 comments:

Post a Comment