动态创建多个tbodies

时间:2013-06-27 20:32:56

标签: c# asp.net webforms html-table

我希望向tbody添加多个asp.net table。 这是我到目前为止所尝试的

TableRow tbody = new TableRow();
tbody.TableSection = TableRowSection.TableBody;
TableRow row = new TableRow();
TableCell cell = new TableCell();
row.Attributes.Add("data-filter", "featured");
cell.Text = "Featured";
row.Cells.Add(cell);
tbody.Controls.Add(row);//throws an error saying tablerow can't have table row as child
Table1.Rows.Add(tbody);

这会抛出一个错误,我不能将表行作为表行的子项,这听起来合法。但我不想排在<tbody>之下,似乎无法弄清楚如何去做。我想要的输出是

<tbody>
      <tr data-filter="featured">
         <td>Featured</td>
      </tr>
</tbody>

1 个答案:

答案 0 :(得分:1)

<tbody>无法使用多个<asp:Table>元素,TableSection属性定义应该呈现该行的“section”,但控件本身仅渲染一个元素TableRowSection

对于异常,您不需要嵌套的TableRow对象,请尝试:

TableRow tbody = new TableRow();
tbody.TableSection = TableRowSection.TableBody;
TableCell cell = new TableCell();
tbody.Attributes.Add("data-filter", "featured");
cell.Text = "Featured";
tbody.Cells.Add(cell);
Table1.Rows.Add(tbody);

这是输出:

<table id="MainContent_Table1">
    <tbody>
        <tr data-filter="featured">
        <td>Featured</td>
        </tr>
    </tbody>
</table>

为了实现你所追求的目标,你可以尝试创建一个自定义控件,或者可能是最简单的解决方案,就是使用HtmlGenericControl并以这种方式构建表元素,而不是最优雅但是它具有所需的结果:

var table = new HtmlGenericControl("table");
var tbody = new HtmlGenericControl("tbody");
var tr = new HtmlGenericControl("tr");
var td = new HtmlGenericControl("td");

tr.Attributes.Add("data-filter", "featured");
td.InnerText = "Featured";
tr.Controls.Add(td);

tbody.Controls.Add(tr);
table.Controls.Add(tbody);

tbody = new HtmlGenericControl("tbody");
tr = new HtmlGenericControl("tr");
td = new HtmlGenericControl("td");
tr.Attributes.Add("data-filter", "featured");
td.InnerText = "Featured";
tr.Controls.Add(td);

tbody.Controls.Add(tr);
table.Controls.Add(tbody);

Page.Controls.Add(table);

这是输出:

<table>
    <tbody>
        <tr data-filter="featured">
            <td>Featured</td>
        </tr>
    </tbody>
    <tbody>
        <tr data-filter="featured">
            <td>Featured</td>
        </tr>
    </tbody>
</table>