Asp.net Create DataTable Dynamically and Bind to Gridview in C#

To implement this requirement we need to create one new datatable after that add columns and bind data to columns after that add those columns to datatable before that first create new website open Default.aspx page and write the following code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamically create datatable and bind data to it in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridviewData();
}
}
/// <summary>
/// Dynamically create & bind data to datatable and bind datatable to gridview
/// </summary>
protected void BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof (string));
dt.Columns.Add("Education", typeof (string));
dt.Columns.Add("Location",typeof(string));


DataRow dtrow = dt.NewRow(); // Create New Row
dtrow["UserId"] = 1; //Bind Data to Columns
dtrow["UserName"] = "Ashish Singh";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Mumbai";
dt.Rows.Add(dtrow);


dtrow = dt.NewRow(); // Create New Row
dtrow["UserId"] = 2; //Bind Data to Columns
dtrow["UserName"] = "Rajesh Singh";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);


dtrow = dt.NewRow(); // Create New Row
dtrow["UserId"] = 3; //Bind Data to Columns
dtrow["UserName"] = "Ankur Srivastava";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
dt.Rows.Add(dtrow);


dtrow = dt.NewRow(); // Create New Row
dtrow["UserId"] = 4; //Bind Data to Columns
dtrow["UserName"] = "Neeraj";
dtrow["Education"] = "CA";
dtrow["Location"] = "Guntur";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}

Post a Comment