Label control child controls

S

SteveM

I recently came accross what I consider strange behavior with the asp:Label
control . I created a simple page that illustrates the issue.

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
Label1.Enabled = ((CheckBox)sender).Checked;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" Checked="true"
AutoPostBack="true" Text="Toggle Enabled"
OnCheckedChanged="CheckBox1_CheckedChanged" />
<asp:Label ID="Label1" runat="server">
<br />Test <asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
</asp:Label>
</div>
</form>
</body>
</html>

When you run this page, you will see the checkbox and the label control
contents (text and edit box). If you click the checkbox, the label control
contents will be displayed as disabled as you woud expect. The oddity
happens when you click the checkbox again. In this case the label doesn't
display at all. On closer inspection, what is happening is that somewhere
after the Page Init event and before the Page Load event the Label control is
removing it's two child controls. The child controls still exist (e.g.,
TextBox1 exists) but their parent properties are null.

Interestingly, I noticed that if the Label control only has one child
control the issue does not occur. That is, the single child control remains
a child of the Label control even after the second click of the checkbox.
This can be demonstrated by wrapping the contents of the label control in a
placeholder control as shown here.

<asp:Label ID="Label1" runat="server">
<asp:placeHolder ID="PlaceHolder1" runat="server">
<br />Test <asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
</asp:placeHolder>
</asp:Label>

With this scenario, the contents of the Label control is disabled and
enabled as you would expect.

I am not asking for tips on how to do the same thing in different ways (I've
already done that). I am curious as to why things happen the way they do
given this scenario. The child controls exist during the Init event so my
guess is that something in the ViewState is causing the Label control to
orphan it's child controls (only if more than one exists), but what?

Thanks for any insight in advance.
- Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top