Friday, 17 April 2015

How to bind DataTable data to Gridview using C#.NET with ASP.NET Dynamically.

How to bind DataTable data to Gridview using C#.NET with ASP.NET Dynamically.

In this article I will explain how to create DataTable and how to bind DataTable data to Gridview Using C#.NET.

To bind DataTable data to gridview we need to write the code like as shown below like ….

<div><asp:GridView ID=" GridView1" runat="server"></asp:GridView></div>

Add below namespaces in code behind…

using System.Data;

 protected void Page_Load(object sender, EventArgs e)
{
BindDataTabelToGridviewData();
}

/// <summary>
/// Dynamically create DataTable & bind data to gridview
/// </summary>

protected void BindGridviewData()
{
        DataTable dtDynamic = new DataTable();

       DataColumn dc = new DataColumn();

        dc = new DataColumn();
        dc.ColumnName = "MatTransSlNo";
        dc.DataType = Type.GetType("System.String");
        dtDynamic.Columns.Add(dc);

        dc = new DataColumn();
        dc.ColumnName = "Amount";
        dc.DataType = Type.GetType("System.Decimal");
        dtDynamic.Columns.Add(dc);

        dc = new DataColumn();
        dc.ColumnName = "DeleteFlag";
        dc.DataType = Type.GetType("System.Int32");
        dtDynamic.Columns.Add(dc);

dtDynamic.Rows.Add(“1”, 101.10,1);
dtDynamic.Rows.Add(“2”, 102.10,0);
dtDynamic.Rows.Add(“3”, 103.10,1);
dtDynamic.Rows.Add(“4”, 104.50,1);

GridView1.DataSource = dtDynamic;
GridView1.DataBind();
}

No comments:

Post a Comment