Here I create a Gridview using a BoundField and also create a paging functionality using EventHandler.
Step 1. Your .aspx page will look like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicGridView.aspx.cs"
Inherits="DynamicGridView" %><!DOCTYPE html PUBLIC "
//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm
1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Step 2. Your .cs page looks like this:
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 DynamicGridView : System.Web.UI.Page
{
DataHelper helper = new DataHelper();
List<Employee> emplist = new List<Employee>();
protected void Page_Load(object sender, EventArgs e)
{
CreateGridView();
}
private void CreateGridView()
{
GridView gv = new GridView();
gv.ID = "EmployeeGridView";
gv.AutoGenerateColumns = false;
gv.AllowPaging = true;
gv.EnableViewState = true;
gv.PageSize = 10; // Default page Size
//Create EventHanfler for Paging.
gv.PageIndexChanging += new GridViewPageEventHandler(this.gv_PageIndexChanging);
helper = new DataHelper();
emplist = helper.GetEmployeeData();
DataTable dt = new DataTable();
if (emplist != null)
{
if (emplist.Count > 0)
{
dt = ListToDataTable(emplist);
//We convert List view to DataTable because we use the
DataTable Column Name as a GridView Column Header.
if (dt != null)
{
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
BoundField boundField = new BoundField();
boundField.DataField = dt.Columns[i].ColumnName.ToString();
boundField.HeaderText = dt.Columns[i].ColumnName.ToString();
gv.Columns.Add(boundField);
}
}
}
}
}
PlaceHolder1.Controls.Add(gv);
BindGridView(gv, dt);
}
private void BindGridView(GridView gv, DataTable dt)
{
gv.DataSource = dt;
gv.DataBind();
}
void gv_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
helper = new DataHelper();
emplist = helper.GetEmployeeData();
DataTable dt = new DataTable();
if (emplist != null)
{
if (emplist.Count > 0)
{
dt = ListToDataTable(emplist);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
BindGridView(gv, dt);
}
}
}
}
}
//Convert List To DataTable.
static DataTable ListToDataTable<T>(IEnumerable<T> list)
{
var dt = new DataTable();
foreach (var info in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (var t in list)
{
var row = dt.NewRow();
foreach (var info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
}
Your output page looks like this: