Hiding a Row in ASP.NET

14 Apr

+ 15

Many things that I come across are “No Duh”. This is one of them.

I frequently see code from other programmers that incorrectly use Panel for
the purpose of hiding content. What they don’t understand is that a Panel tag
renders a table, and as such can’t be used around Table Rows. For instance,

  1 <asp:panel id="test" visible="True" runat="server">
  2    Ewoks aren't mini-wookies.
  3 </asp:panel> 

will render as:

  1 <table id="test" cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td>
  2   Ewoks aren't mini-wookies.
  3 </td></tr></table>

that means you can’t do something like:

  1 <tr>
  2 	<th>name:</th>
  3 	<td>something...</td>
  4 </tr>
  5 <asp:Panel ID="test" Runat="server" Visible="True">
  6 	<tr>
  7 		<th>date of birth:</th>
  8 		<td>something...</td>
  9 	</tr>
 10 </asp:Panel>
 11 <tr>
 12 	<th>email:</th>
 13 	<td>something...</td>
 14 </tr>

To do so will create a table between two rows. The reason this has gone
unnoticed by many developers is that they are developing for Internet Explorer
exclusively, which will forgive some of these mistakes. Firefox shows them clear
as day.

I was thinking about a solution this morning, wondering if I would have to
create my own Panel control which renders no table, but thought I would try the
obvious first. Could I just do this?:

  1 <tr>
  2 	<th>name:</th>
  3 	<td>something...</td>
  4 </tr>
  5 <tr id="Tr1" runat="server">
  6 	<th>date of birth:</th>
  7 	<td>something...</td>
  8 </tr>
  9 <tr>
 10 	<th>email:</th>
 11 	<td>something...</td>
 12 </tr>

And then use the following in the code behind?:

  1 protected HtmlControls.HtmlTableRow Tr1;
  3 private void Page_Load(object sender, EventArgs e)
  4 {
  5    Tr1.Visible = false;
  6 }

Sure enough it hid the row!