代码之家  ›  专栏  ›  技术社区  ›  Ken Paul

如何将.NET TableCell呈现为th而不是td?

  •  4
  • Ken Paul  · 技术社区  · 16 年前

    我正在动态构建一个.NET表,包括带有TablesSection集的TableRows,结果是1 thead行和多个tbody行。现在我需要让thead行中的tablecells用th标记而不是td标记来呈现。我该怎么做?我还没有为此找到TableCell属性,它将允许我向RowCells集合中添加文本。

    3 回复  |  直到 9 年前
        1
  •  13
  •   Oleks    16 年前

    你试过了吗? TableHeaderCell ?

        2
  •  0
  •   derek    16 年前

    你可以使用 HtmlGenericControl th = new HtmlGenericControl("th") 然后把它添加到thead行。

        3
  •  0
  •   MPaul    10 年前

    另一个解决方案是继承 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>
        }
    

    此解决方案允许您从一个类继承,而不是同时从两个类继承 表格单元 和 TableHeaderCell 如果您希望分别自定义它们。

    编辑

    这个 Type 中的属性 if 语句是类的自定义属性,我在其中添加了 enum 简化适用的类型。

    public enum CellType
    {
        td,
        th
    }
    
    private CellType _Type;
    public CellType Type
    {
        get { return _Type; }
        set { _Type = value; }
    }
    
    推荐文章