0

我希望将多个添加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>
4

1 回答 1

1

多个<tbody>元素是不可能的<asp:Table>,该TableSection属性定义了应该在其中呈现行的“部分”,但是控件本身每个只呈现一个元素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>
于 2013-06-27T21:11:50.147 回答