In this article I will explain
how to create dynamic DataTable and bind data to columns in dynamic DataTable
using ASP.NET.
First Open new website , Right
click and add new page with the name as DynamicallyCreateDataTable.aspx after that we need to create one new DataTable
after that add columns with DataTypes and bind data to columns after that add
those columns to DataTable.
Output:
Before we need to design DynamicallyCreateDataTable.aspx page design. Below is the design code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamically create datatable with Dynamic columns and bind data to
GridView in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<table align="center">
<tr>
<td>
<asp:GridView ID="gvDynamicallyDataTable" runat="server" HeaderStyle-ForeColor="Maroon">
</asp:GridView>
</td>
</tr>
</table>
</form>
</body>
</html>
// add the following
namespace references
using
System;
using
System.Data;
//After add namespaces write the
following code in code behind
public partial class DynamicallyCreateDataTable : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
if (!IsPostBack)
{
DynamicallyCreateDataTableGrid();
}
}
protected void DynamicallyCreateDataTableGrid()
{
// Dynamically create DataTable and Dynamic columns with
datatypes
DataTable dt
= new DataTable();
dt.Columns.Add("StudentID", typeof(Int32));
dt.Columns.Add("Student Name", typeof(string));
dt.Columns.Add("School Name", typeof(string));
dt.Columns.Add("Class Name", typeof(string));
dt.Columns.Add("Section Name", typeof(string));
dt.Columns.Add("Rank No", typeof(Int32));
// First record added to DataTable
DataRow
dtrow = dt.NewRow(); // Create New Row
dtrow["StudentID"] = 1; //Bind Data to Columns
dtrow["Student
Name"] = "Satya";
dtrow["School
Name"] = "Narayana School";
dtrow["Class
Name"] = "Seventh class";
dtrow["Section
Name"] = "A";
dtrow["Rank
No"] = 3;
dt.Rows.Add(dtrow);
// Secound record added to DataTable
dtrow = dt.NewRow(); // Create New Row
dtrow["StudentID"] = 2; //Bind Data to Columns
dtrow["Student
Name"] = "Bharath";
dtrow["School
Name"] = "Chaithanya School";
dtrow["Class
Name"] = "Fifth Class";
dtrow["Section
Name"] = "A";
dtrow["Rank
No"] = 8;
dt.Rows.Add(dtrow);
// 3rd record added to DataTable
dtrow = dt.NewRow(); // Create New Row
dtrow["StudentID"] = 3; //Bind Data to Columns
dtrow["Student
Name"] = "Chaithanya";
dtrow["School
Name"] = "Gayatri School";
dtrow["Class
Name"] = "Forth Class";
dtrow["Section
Name"] = "A";
dtrow["Rank
No"] = 5;
dt.Rows.Add(dtrow);
// 4th record added to DataTable
dtrow = dt.NewRow(); // Create New Row
dtrow["StudentID"] = 4; //Bind Data to Columns
dtrow["Student
Name"] = "Pardhu";
dtrow["School
Name"] = "Gagri School";
dtrow["Class
Name"] = "Forth Class";
dtrow["Section
Name"] = "A";
dtrow["Rank
No"] = 10;
dt.Rows.Add(dtrow);
gvDynamicallyDataTable.DataSource = dt;
gvDynamicallyDataTable.DataBind();
}
}
Output:
No comments:
Post a Comment