Tuesday, August 14, 2012

Example : How to bind GridView in asp.net

In this article I will illustrate how to bind GridView from SQL DataSource in asp.net.

Open Visual Studio. 
From File menu option , Select NewWebsite .
From the templates , select Asp.NetWebsite and name it.

default.aspx is the default file created when new website is created.

Double click on "default.aspx" page , and drag and drop Gridview Control on to the design view of aspx page. (Rename gridview control if u want)

Now open default.aspx.cs file either by double click on that file or right click in the aspx page and select ViewCode.

Write the following code and execute..


using System;
/*USE THESE NAMESPACES FOR CREATING DATABASE CONNECTION*/
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
/*USE THESE NAMESPACES IF CONNECTION STRING IS DEFINED IN WEB.CONFIG FILE*/
using System.Configuration;

public partial class UrWebsiteName : System.Web.UI.Page

{
    /*DECLARE CONNECTION VARIABLES*/
    SqlConnection Con;
    SqlCommand Cmd;
    SqlDataAdapter Adp;
    DataTable Dt;


 protected void Page_Load(object sender, EventArgs e)
    {
        /*Open database Connection*/
        Con = new SqlConnection("Data Source=172.162.35.36;Initial Catalog=MyDb;User  ID=abc;Password=133");

        Con.Open();

        /*Write Sql Command*/
        Cmd = new SqlCommand("Select * from temp", Con);

        /* SqlDataAdapter to fill datatable with result set.*/

        Adp = new SqlDataAdapter(Cmd);
        Cmd.ExecuteNonQuery();
        Dt = new DataTable();
        Adp.Fill(Dt);

        /*Bind the grid with the datatable*/
        GvTable.DataSource = Dt;
        GvTable.DataBind();
    }
}





No comments:

Post a Comment