Designer source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>gridview header</title>
<style type="text/css">
.header {
background-color:#3E3E3E;
font-family:Calibri;
color:White;
text-align:center;
line-height:25px;
}
.rowstyle {
font-family:Calibri;
line-height:25px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>
C# 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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.ReadXml(Server.MapPath("EmployeeDetails.xml"));
GridView gvEmployee = new GridView();
gvEmployee.AutoGenerateColumns = false;
if (ds != null && ds.HasChanges())
{
dt = ds.Tables[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();
gvEmployee.Columns.Add(boundfield);
}
gvEmployee.DataSource = dt;
gvEmployee.DataBind();
gvEmployee.Width = 600;
gvEmployee.HeaderStyle.CssClass = "header";
gvEmployee.RowStyle.CssClass = "rowstyle";
Panel1.Controls.Add(gvEmployee);
}
}
}
- See more at: http://www.dotnetfox.com/articles/create-dynamic-gridview-or-programmatically-create-Asp-Net-gridview-with-dynamic-boundfield-1083.aspx#sthash.EtduYuxk.dpuf