articles

Home / DeveloperSection / Articles / Bind Data to GridView in ASP.Net

Bind Data to GridView in ASP.Net

mohan kumar15119 03-Nov-2011

This is my first article. In this article I have shown you how to load a GridView Using Stored Procedure.

Stored Procedure:-
createprocedure usp_GetEmployeeDetails
as
begin
select eid,ename,eaddress,ecity,estate from employee
end
Default.aspx:-
 <%@PageLanguage="C#"AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default"%>
 
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
    <title>A Sample Program Illustrating The Data Retrieval Using Stored Procedure</title>
</head>
<body>
    <formid="form1"runat="server">
    <div>
        <asp:GridViewID="GridView1"runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

 Default.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Windows.Forms;
 
publicpartialclass_Default : System.Web.UI.Page
{
    SqlConnection conn = newSqlConnection("Data Source=INNOVA14;uid=sa;pwd=innova;Initial Catalog=Employee");
    protectedvoid Page_Load(object sender, EventArgs e)
    {
        loadmyGridUsingStoredProcedure();
    }
 
    publicvoid loadmyGridUsingStoredProcedure()
    {
        conn.Open();
        SqlDataAdapter sda = new SqlDataAdapter("usp_GetEmployeeDetails", conn);
        SqlCommand comm = newSqlCommand();
        comm.CommandType = CommandType.StoredProcedure;
        DataTable dt = newDataTable();
        sda.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        conn.Close();
    }
}

Updated 04-Mar-2020
Having around 5 Years experience in .NET domain.

Leave Comment

Comments

Liked By