ASP.NET GridView control is one of the data binding control most often used .But it has one problem that when rendering on browser it generate all rows including header and footer in <tbody >section rather than creating separate <thead> and <tfoot>.This is how GridView is rendered as html.Note that even header is generated as row in tbody section.
- <table id="MainContent_grdNormal" >
- <tbody>
- <tr class="header content-wrapper" >
- <th scope="col">EmpId</th>
- <th scope="col">EmpName</th>
- <th scope="col">City</th>
- </tr>
- <tr>
- <td>L1Z 5F4</td>
- <td>Nathaniel</td>
- <td>Ilbono</td>
- </tr>
- <tr >
- <td>B7F 4U4</td>
- <td>Ross</td>
- <td>Dover</td>
- </tr>
- <tr>
- <td>R9C 1T9</td>
- <td>Patrick</td>
- <td>Edam</td>
- </tr>
- </tbody>
- </table>
Now to force a Gridview to render <thead> and <tfoot>,we need to add 3 lines of code after grid is binded. Below is the code to achieve the same.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- namespace GridHeaders {
- public partial class _Default: Page {
- protected void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- gridbind();
- AddHeaders();
- }
- }
- protected void AddHeaders() {
- if (grdNormal.Rows.Count > 0) {
-
- grdNormal.UseAccessibleHeader = true;
-
- grdNormal.HeaderRow.TableSection = TableRowSection.TableHeader;
-
- grdNormal.FooterRow.TableSection = TableRowSection.TableFooter;
- }
- }
- protected void gridbind() {
- DataTable dt = new DataTable();
- dt.Columns.Add("EmpId", typeof(string));
- dt.Columns.Add("EmpName", typeof(string));
- dt.Columns.Add("City", typeof(string));
- DataRow dr1 = dt.NewRow();
- dr1[0] = "L1Z 5F4";
- dr1[1] = "Nathaniel";
- dr1[2] = "Ilbono";
- dt.Rows.Add(dr1);
- DataRow dr2 = dt.NewRow();
- dr2[0] = "B7F 4U4";
- dr2[1] = "Ross";
- dr2[2] = "Dover";
- dt.Rows.Add(dr2);
- DataRow dr3 = dt.NewRow();
- dr3[0] = "R9C 1T9";
- dr3[1] = "Patrick";
- dr3[2] = "Edam";
- dt.Rows.Add(dr3);
- grdNormal.DataSource = dt;
- grdNormal.DataBind();
- }
- }
- }
Note: Call AddHeaders() method after binding Gridview otherwise you will get table must contain row sections in order of header, body, then footer error.