无法在asp.net中呈现thead或tfoot标签

时间:2014-08-05 15:30:54

标签: c# asp.net

根据this post

  

创建Table对象时,请包含TableHeaderRow和   TableHeaderCell控件。 TableHeaderRow和的默认值   TableFooterRow控件使控件呈现thead,tbody和   tfoot元素

我一直试图让theadtfoot代码无法成功呈现。

我正在使用我发布的链接中提到的类,我只使用一堆嵌套的tbody标记得到tr。我正在使用VS2012 pro和.net 4.5。

我做错了什么?

public void BuildHTMLTable(DataTable dt)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter w = new HtmlTextWriter(sw);

    Table tbl = new Table();

    // create table header
    TableHeaderRow thr = new TableHeaderRow();
    foreach (DataColumn col in dt.Columns)
    {
        TableHeaderCell thc = new TableHeaderCell();
        thc.Text = col.Caption;
        thr.Cells.Add(thc);
    }
    tbl.Rows.AddAt(0, thr);

    // write out each data row
    foreach (DataRow row in dt.Rows)
    {
        TableRow tr = new TableRow();
        foreach (var value in row.ItemArray)
        {
            TableCell td = new TableCell();
            td.Text = value.ToString();
            tr.Controls.Add(td);
        }
        tbl.Rows.Add(tr);
    }

    // Create table footer
    TableFooterRow tfr = new TableFooterRow();
    foreach (DataColumn col in dt.Columns)
    {
        TableCell th = new TableCell();
        th.Text = col.Caption;
        tfr.Cells.Add(th);
    }
    tbl.Rows.Add(tfr);

    // Renter the table to html writer
    tbl.RenderControl(w);
    // copy html writer to a string variable
    tableString = sw.ToString();
}

在HTML下面呈现HTML

rendered html

1 个答案:

答案 0 :(得分:3)

更改TableHeaderRow和TableFooterRow的TableSection值。

public void BuildHTMLTable(DataTable dt)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter w = new HtmlTextWriter(sw);

    Table tbl = new Table();

    // create table header
    TableHeaderRow thr = new TableHeaderRow();
    thr.TableSection = TableRowSection.TableHeader; // ADD THIS LINE

    foreach (DataColumn col in dt.Columns)
    {
        TableHeaderCell thc = new TableHeaderCell();
        thc.Text = col.Caption;
        thr.Cells.Add(thc);
    }
    tbl.Rows.AddAt(0, thr);

    // write out each data row
    foreach (DataRow row in dt.Rows)
    {
        TableRow tr = new TableRow();
        foreach (var value in row.ItemArray)
        {
            TableCell td = new TableCell();
            td.Text = value.ToString();
            tr.Controls.Add(td);
        }
        tbl.Rows.Add(tr);
    }

    // Create table footer
    TableFooterRow tfr = new TableFooterRow();
    tfr.TableSection = TableRowSection.TableFooter; // ADD THIS LINE
    foreach (DataColumn col in dt.Columns)
    {
        TableCell th = new TableCell();
        th.Text = col.Caption;
        tfr.Cells.Add(th);
    }
    tbl.Rows.Add(tfr);

    // Renter the table to html writer
    tbl.RenderControl(w);
    // copy html writer to a string variable
    tableString = sw.ToString();
}