Dynamically add rows and columns in data table, also bind Gridview with data table

First create instance of DataTable class, which is inside in System.Data namespace. After that you make columns and rows inside the DataTable. First create columns with their data type also insert rows data in it.

Source Code

<div>
        <asp:GridView ID="GridView1" runat="server">
        <HeaderStyle BackColor ="Green" ForeColor ="Orange" />
        <RowStyle BackColor ="Black" ForeColor ="White" />

        </asp:GridView><br />

        <asp:Button ID="B1" runat="server" Text="Bind GridView" onclick="B1_Click" />
    
    </div>

Business Logic Code

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

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


    protected void B1_Click(object sender, EventArgs e)
    {
  
DataTable datatable = new DataTable();
datatable.Columns.Add("serial Number", typeof(Int32));
datatable.Columns.Add("Name", typeof(string));
datatable.Columns.Add("Address", typeof(string));
datatable.Rows.Add(1, "Jacob", "USA");
datatable.Rows.Add(2, "Lefore", "USA");
datatable.Rows.Add(3, "Bill", "UK");
datatable.Rows.Add(4, "Smith", "UK");
GridView1 .DataSource =datatable;
            GridView1.DataBind ();

    }
}

Code Generate the following Output

Dynamically add rows and columns in data table, also bind Gridview with data table

Dynamically add rows and columns in data table, also bind Gridview with data table Dynamically add rows and columns in data table, also bind Gridview with data table Reviewed by Jacob Lefore on May 31, 2014 Rating: 5

No comments