Posts Tagged ‘bind datatable to datagrid in ASP.Net’
How to Create a Data Table Dynamically with sample data and Bind to Grid/Create datatable with sample data.
September 7, 2012
4 comments
How to create a datatable with sample data
We are going to demonstrate how to create a sample datatable dynamically in ASP.Net. Here we are creating a ASPx page with a grid view. In the page load of the ASPx page will call a bind method which creating a datatable dynamically and bind the datatable with datagrid. In BindGridviewData function create data for an employee and binding employee data to the employee grid.
ASPxPage
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicCreateDataTable.aspx.cs" Inherits="ExperimentLab.DynamicCreateDataTable" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="gdEmployee" runat="server"> </asp:GridView> </div> </form> </body> </html>
Code Behind
protected void Page_Load(object sender, EventArgs e) { BindGridviewData(); } //Creating datatable dynamically and bind data to a grid protected void BindGridviewData() { DataTable dt = new DataTable(); //Create datatable Columns dynamically dt.Columns.Add("EmployeeID", typeof(Int32)); dt.Columns.Add("EmployeeName", typeof(string)); dt.Columns.Add("Department", typeof(string)); dt.Columns.Add("City", typeof(string)); //Create data table row dynamically add DataRow dtrow = dt.NewRow(); // Create New Row //Assign data to datarow dynamically dtrow["EmployeeID"] = 1; //Bind Data to Columns dtrow["EmployeeName"] = "Ramraj"; dtrow["Department"] = "Admin"; dtrow["City"] = "Calicut"; dt.Rows.Add(dtrow); dtrow = dt.NewRow(); // Create New Row //Assign data to datarow dynamically dtrow["EmployeeID"] = 2; //Bind Data to Columns dtrow["EmployeeName"] = "Malhothra"; dtrow["Department"] = "HR"; dtrow["City"] = "Mumbai"; dt.Rows.Add(dtrow); dtrow = dt.NewRow(); // Create New Row //Assign data to datarow dynamically dtrow["EmployeeID"] = 3; //Bind Data to Columns dtrow["EmployeeName"] = "Sinan Hafis"; dtrow["Department"] = "Admin"; dtrow["City"] = "Delhi"; dt.Rows.Add(dtrow); dtrow = dt.NewRow(); // Create New Row //Assign data to datarow dynamically dtrow["EmployeeID"] = 4; //Bind Data to Columns dtrow["EmployeeName"] = "Wazim Jafar"; dtrow["Department"] = "Finance"; dtrow["City"] = "Goa"; dt.Rows.Add(dtrow); gdEmployee.DataSource = dt; gdEmployee.DataBind(); } RESULT
Recent Comments