ASP.NET Labels with Associated Controls inside of User Controls

I've been trying to use labels with the AssociatedControlID property more often.  If you aren't familiar with this property, it changes the behavior of the Label control.  Rather than rendering the typical <span> html element, the Label control will now render a <label> html element with the for property set.  This links the label to another server control.  This is good for accessibility, allows hotkeys to be set for the associated control, and also allows the user to click on the label in order to give focus to the associated control. Syntax is as follows

<asp:Label Text="<u>S</u>earch" AssociatedControlID="txtSearch" AccessKey="s" ID="lblSearch" runat="server" />
<asp:TextBox ID="txtSearch" runat="server" />

In this example, pressing Alt+S (or Ctrl+Alt+S in Firefox), or clicking on the label will give focus to the textbox.

But what if the control you want to target is actually inside of an user control.  This is the problem that I faced recently.  Lets say you have an instance of an user control with the id EmailInput1.  This user control has a textbox txtEmail.  To target this textbox from your aspx page, set the AssociatedControlID property to "EmailInput1:txtEmail".  Just parent -> child with a colon separator.  Easy enough!

1 Comment

Comments have been disabled for this content.