utorok 14. augusta 2007

ASP.NET - DataGrid rendered with thead, tbody, th, ....

By default DataGrid is rendered with tags <table>, <tr> and <td>. To make styling with CSS easier it would also suitable to render also tags <thead>, <tbody>, <th> etc. To solve this problem I created custom DataGrid derived from System.Web.UI.WebControls.DataGrid, where in overriden method OnPreRender are realized modifications:


   1:  using System;

   2:  using System.Reflection;

   3:  using System.Web.UI;

   4:  using System.Web.UI.WebControls;

   5:   

   6:  namespace NMarian.Controls

   7:  {

   8:      public class DataGrid : System.Web.UI.WebControls.DataGrid

   9:      {

  10:          protected override void OnPreRender(EventArgs e)

  11:          {

  12:              Table table = Controls[0] as Table;

  13:   

  14:              if (table != null && table.Rows.Count > 0)

  15:              {

  16:                  table.Rows[0].TableSection = TableRowSection.TableHeader;

  17:                  table.Rows[table.Rows.Count - 1].TableSection = TableRowSection.TableFooter;

  18:   

  19:                  FieldInfo field = typeof(WebControl).GetField("tagKey", BindingFlags.Instance | BindingFlags.NonPublic);

  20:   

  21:                  foreach (TableCell cell in table.Rows[0].Cells)

  22:                  {

  23:                      field.SetValue(cell, HtmlTextWriterTag.Th);

  24:                  }

  25:              }

  26:   

  27:              base.OnPreRender(e);

  28:          }

  29:      }

  30:  }

1 komentár:

Ivan Tapia povedal(a)...

Excelent answer... I'm from Perú, and your code aid me a lot!!.
Thank you so much.