Here was an odd thing. Take one repeater
Bind it up to something and get a list of textboxes and checkboxes. Like so
<asp:Repeater runat="server">
<ItemTemplate>
<asp:CheckBox ID="chkBox1" AutoPostBack="true"
OnCheckedChanged="CheckBox_Click" runat="server" />
<asp:TextBox ID="txtBox1" runat="server" /><br />
</ItemTemplate>
</asp:Repeater>
Bind it up to something and get a list of textboxes and checkboxes. Like so

The task is to wire up the Checkbox click event so that when it is clicked the corresponding textbox is disabled i.e.

Easy peasy I thought and wired it up with this code
protected void CheckBox_Click(object sender, EventArgs e)
{
CheckBox myCheckbox = (CheckBox)sender;
TextBox textBox = (TextBox)Page.FindControl("textBoxId");
textBox.Enable = !myCheckbox.Enable;
}
The surprising result is that no matter which checkbox is clicked it is always the first textbox that is disabled. The problem is with finding the control. The line fourth line has changed -
protected void CheckBox_Click(object sender, EventArgs e)
{
CheckBox myCheckbox = (CheckBox)sender;
TextBox textBox = (TextBox)myCheckbox.NamingContainer.FindControl("textBoxId");
textBox.Enable = !myCheckbox.Enable;
}
I suddenly realised what a NamingContainer was. Previously I just thought it was a piece of arcane .Net knowledge – defined in MSDN as
Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same ID.
Yeah right whatever. Well apparently it’s actually important stuff.
In the first example the code finds the first textBox called “textboxId” in the page. This is always the first one hence my code doesn’t work. In the second, corrected code – the control is searched for within the NamingContainer of the event sender – in this case it’s the RepeaterItem. So in the repeater there are any number of texboxes called “textboxId” but the don’t clash and can be accessed because each one exists in it’s own NamingContainer – i.e. unique naming space.
I appreciate this will be obvious stuff to many people but I felt like a super-brained coding rock star when I found this out. Then again I’m easily impressed.
No comments:
Post a Comment