sobota 14. júla 2007

ASP.NET - DataGrid renderovaný s thead, tbody, th, ....

Štandartne sa DataGrid renderuje tagmi <table>, <tr> a <td>. Pre zjednodušenie štýlovania tabuľky pomocu CSS je vhodné okrem spomínaných tagov renderovať aj tágy <thead>, <tbody>, <th> a podobne. Na riešenie tohto problému som vytvoril vlastný DataGrid odvodený od System.Web.UI.WebControls.DataGrid pričom v prekrytej metóde OnPreRender sú vykonané všetky potrebné úpravy:


   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:  }

2 komentáre:

Anonymný povedal(a)...

Ani nie tak pre zjednodusenie stylovania ako pre pridanie trosky semanticity do html kodu. Videl si kod renderovany datagridom, prip. gridview po aplikovani CSS Friendly Control Adapters?

Marián Košťál povedal(a)...

Ano videl, ale CSS Friendly Control Adapters obsahuju adapter iba pre GridView, pre DataGrid nie. Urcite by sa dal taky adapter napisat, ale nechcelo sa mi to :)