How to create thead and tbody in ASP.NET Table ?
asp:Table does not support these elements.
Update: As jameh's answer reveals, the sentence above is completely wrong: the
TableSection
property allows to control whether a given row goes into the table's header, body or footer.
To elaborate on his answer, it seems you can even achieve this declaratively by setting the TableSection
property in your markup, without code behind:
<asp:Table id="yourId" runat="server"> <asp:TableHeaderRow TableSection="TableHeader"> <!-- ... --> </asp:TableHeaderRow> <asp:TableRow> <!-- 'TableSection' defaults to 'TableRowSection.TableBody'. --> <!-- ... --> </asp:TableRow> <asp:TableRow TableSection="TableFooter"> <!-- ... --> </asp:TableRow></asp:Table>
Original, now moot answer follows:
You might want to try the HtmlTable class instead:
<table id="yourId" runat="server"> <thead> . . . </thead> <tbody> . . . </tbody></table>
Frédéric's answer is not accurate. asp:Table DOES in fact support <tbody>
and <thead>
tags, but in a less obvious fashion than HtmlTable.
UseAccessibleHeader is true by default for tables, which means your header rows will be rendered properly with <th>
instead of <td>
, but to get the <tbody>
and <thead>
tags, you've just got to set some voodoo at Page_Load and when you're creating/inserting your rows in the codebehind.
Here's my example asp:Table markup:
<asp:Table runat="server" ID="tblGeneral"> <asp:TableHeaderRow ID="TableHeaderRow1" runat="server"> <asp:TableHeaderCell ID="TableHeaderCell1" runat="server">Column 1</asp:TableHeaderCell> <asp:TableHeaderCell ID="TableHeaderCell2" runat="server">Column 2</asp:TableHeaderCell> <asp:TableHeaderCell ID="TableHeaderCell3" runat="server">Column 3</asp:TableHeaderCell> <asp:TableHeaderCell ID="TableHeaderCell4" runat="server">Column 4</asp:TableHeaderCell> <asp:TableHeaderCell ID="TableHeaderCell5" runat="server">Column 5</asp:TableHeaderCell> </asp:TableHeaderRow></asp:Table>
At Page_Load, we specify that our TableHeaderRow1 should be a TableHeader:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load TableHeaderRow1.TableSection = TableRowSection.TableHeader End Sub
And finally, in your function that inserts rows into said table, you just have to specify that the TableRowSection of each row you add is a TableBody:
Dim row As TableRowDim dvRow As Data.DataRowViewFor Each dvRow In dv row = New TableRow row.TableSection = TableRowSection.TableBody 'THIS is the important bit cell = New TableCell Col1Stuff = New Label Col1Stuff.Text = "Blah" cell.Controls.Add(Col1Stuff) row.Cells.Add(cell) ...tblGeneral.Rows.Add(row)Next
You can do more reading on the TableRowSection property; looks like you can also accomplish this with your asp:Table template.