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>
- 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) {
- //This replaces <td> with <th>
- grdNormal.UseAccessibleHeader = true;
- //This will add the <thead> and <tbody> elements
- grdNormal.HeaderRow.TableSection = TableRowSection.TableHeader;
- //This adds the <tfoot> element. Remove if you don't have a footer row
- 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();
- }
- }
- }

Sara RodriguezPosted Jun 24, 2016, 4:36 PM
Is there a way to do this with custom generated header rows that are created in the rowCreated event under "(e.Row.RowType == DataControlRowType.Header){}"? I have custom headers and do not use the auto-generated gridview headers.