动态创建多个tbody
本文关键字:tbody 创建 动态 | 更新日期: 2023-09-27 18:20:15
我希望将多个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>
<asp:Table>
不可能有多个<tbody>
元素,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>