malkassem
malkassem

Reputation: 1957

How do I set html table caption from code behind? ASP.NET

I have a table in my aspx page:

<table id="tbl" runat="server">
</table>

I need to set to set the table caption in the code behind, so that it renders as follows:

<table id="tbl" runat="server">
   <caption>Monthly savings</caption>
</table>

Any help will be greatly appreciated.

Upvotes: 0

Views: 3237

Answers (3)

Ricardo Rodrigues
Ricardo Rodrigues

Reputation: 2268

The previous response from Brad M is almost correct, you must add a runat="server" attribute, an ID attribute and set it to some value you see fit, and then on the server side code:

One big caveat thought, you need to place the caption before the table element, inside is not possible

idYouGave.InnerText = "Monthly savings";

Since you can't use the directly inside the , do something like this to achieve what you want:

<tr>
  <th colspan="numOfCols"><caption>...</caption></th>
</tr>

Upvotes: 1

Andrei
Andrei

Reputation: 56716

It is not possible. Control HtmlTable can contain <tr> and only them, everything else will be removed. Here is the full note from MSDN:

A complex table model is not supported. You cannot have an HtmlTable control with nested <caption>, <col>, <colgroup>, <tbody>, <thead>, or <tfoot> elements. These elements are removed without warning and do not appear in the output HTML. An exception will be thrown if you attempt to programmatically add these table model elements to the Control.Controls collection of the HtmlTable control.

Your options are either to switch to asp:Table control, or switch back to plain markup.

Upvotes: 1

Brad M
Brad M

Reputation: 7898

Just add the runat="server" attribute to your caption element, as well as give it an ID. Then just refer to it in code behind as caption.InnerText = "Monthly savings";

Upvotes: 1

Related Questions