开发者

How do I render .NET TableCell as TH instead of TD?

开发者 https://www.devze.com 2022-12-31 13:45 出处:网络
I\'m dynamically building a .NET Table, including TableRows with TablesSection set, resulting in 1 THEAD row and multiple TBODY rows.Now I need to get the TableCells in the THEAD row to render with TH

I'm dynamically building a .NET Table, including TableRows with TablesSection set, resulting in 1 THEAD row and multiple TBODY rows. Now I need to get the TableCells in the THEAD row to render with TH tags rather than TD tags. How do I do that? I haven't found a TableCell attribute for that, and it won let me add Liter开发者_C百科als to the row Cells collection.


Have you tried TableHeaderCell?


You can use HtmlGenericControl th = new HtmlGenericControl("th") and add that to the thead row.


Another solution is to inherit the TableCell class and overwrite the Render method.

This gives you the ability to truly customize your WebControl as well as add additional methods that may benefit your particular scenario.

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

This solution allows you to inherit from one class as opposed to both TableCell and TableHeaderCell in the event you wish to customize them respectively.

EDIT

The Type property in the if statement is a custom property of the class, in which I've added an enum to simplify the applicable types.

public enum CellType
{
    td,
    th
}

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

精彩评论

暂无评论...
验证码 换一张
取 消