另请参阅相关问题,我们可以在同一<表>中有多个<正文>吗?正文>表>
假设我想使用 asp:table 生成下表:
<table>
<thead>
...stuff...
</thead>
<tbody class="odd">
<th scope="tbody">CUSTOMER 1</th>
<tr><td>#1</td><td>January</td></tr>
<tr><td>#2</td><td>April</td></tr>
<tr><td>#3</td><td>March</td></tr>
</tbody>
<tbody class="even">
<th scope="tbody">CUSTOMER 2</th>
<tr><td>#1</td><td>January</td></tr>
<tr><td>#2</td><td>April</td></tr>
<tr><td>#3</td><td>March</td></tr>
</tbody>
<tbody class="odd">
<th scope="tbody">CUSTOMER 3</th>
<tr><td>#1</td><td>January</td></tr>
<tr><td>#2</td><td>April</td></tr>
<tr><td>#3</td><td>March</td></tr>
</tbody>
</table>
我可以通过编程方式构建这些<tbody>
/<tr>
元素吗?
我尝试做这样的事情:
var x = new HtmlGenericControl("tbody");
x.Attributes["class"] = jobNum % 2 == 0 ? "even" : "odd";
TableRow xinfoRow = buildXInfoRow(job); x.Controls.Add(xinfoRow);
TableRow xdescriptionRow = buildXDescriptionRow(job); x.Controls.Add(xdescriptionRow);
myTable.Controls.Add(x);
但这只会给我错误'Table' cannot have children of type 'HtmlGenericControl'
.
TableCell、TableHeaderRow、TableHeaderCell 等类,但我似乎找不到 TableBody 或 TableHeader。我可以在页眉、正文或页脚中放置行:
descriptionRow.TableSection = TableRowSection.TableBody;
。但我似乎无法将这些行分成多个不同的<tbody>
元素。我几乎已经放弃了,转而使用<asp:ListView>
来生成表,但我有兴趣看看是否可以做到这一点。
仅凭其属性无法增强asp:Table
<tbody>
的功能。但是我知道有三种方法可以实现这一点:
-
创建一个派生自
System.Web.UI.WebControls.Table
的类,并使用您自己的逻辑重写其方法RenderContents
。查看 .NET Framework 本机方法的默认实现 (Table.RenderContents
),了解如何使用任何反汇编器(如 .NET Reflector)来管理它。 -
(最难的方法)使用子类(TableBody,TableBodyRow,TableBodyCell等)创建自己的
asp:Table
;) -
请改用
asp:Repeater
,如下所示:
<asp:Repeater ...>
<HeaderTemplate>
<table>
<thead>
..stuff..
</thead>
<tbody class="odd">
</HeaderTemplate>
<ItemTemplate>
<tr> ..stuff.. </tr>
</ItemTemplate>
<SeparatorTemplate>
<asp:PlaceHolder Visible='<%# (Container.ItemIndex + 1) % 3 %>' runat="server">
<tbody class="<%# (Container.ItemIndex + 1) % 6 > 3 ? "even" : "odd" %>">
</asp:PlaceHolder>
</SeparatorTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
甚至使用子中继器(如果您有两个集合 - 按月划分的客户和值,可能是更好的方法)
PS:通过查看您的示例,<tbody>
内部的<th>
在HTML规则方面是不正确的。不要在那里使用它。