2010-05-19 64 views
3

我正在動態構建一個.NET表,其中包括TableRows和TablesSection集,導致1個THEAD行和多個TBODY行。現在我需要讓THEAD行中的TableCells使用TH標籤而不是TD標籤進行渲染。我怎麼做?我還沒有找到一個TableCell屬性,它贏得了讓我添加Literals行Cell集合。如何將.NET TableCell呈現爲TH而不是TD?

回答

12

你試過TableHeaderCell

+1

現在我的額頭疼得要命。非常感謝。 – 2010-05-19 18:24:12

0

您可以使用HtmlGenericControl th = new HtmlGenericControl("th")並將其添加到thead行。

+0

如何將它添加到行中?使用row.Cells.Add(mycell)給出編譯時錯誤,並且row.Controls.Add(mycell)給出運行時錯誤。 – 2010-05-19 18:19:33

0

另一種解決方案是繼承TableCell類並覆蓋Render方法。

這使您能夠真正定製您的WebControl以及添加可能有利於您的特定場景的其他方法。

protected override void Render(HtmlTextWriter writer) 
    { 
     if (Type == CellType.th) 
     { 
      writer.Write(HtmlTextWriter.TagLeftChar + "th"); // Render <th 
      Attributes.Render(writer); // Render any associated attributes 
      writer.Write(HtmlTextWriter.TagRightChar); // Render > 
      base.RenderContents(writer); // Render the content between the <th></th> tags 
      writer.Write(HtmlTextWriter.EndTagLeftChars + "th" + HtmlTextWriter.TagRightChar); // Render </th> 
     } 
     else 
      base.Render(writer); // Defaults to rendering <td> 
    } 

該解決方案可以讓你從一個類繼承,如你想分別自定義它們的事件不是都TableCellTableHeaderCell

編輯

Type財產在if聲明是類,其中我已經添加了一個enum簡化適用類型的自定義屬性。

public enum CellType 
{ 
    td, 
    th 
} 

private CellType _Type; 
public CellType Type 
{ 
    get { return _Type; } 
    set { _Type = value; } 
}