Linking a .Net Label Control with an input

In standard HTML label tags are used to assign some text to an input inside a form, giving the user the option to click the text in the label and causing the assigned input to be clicked too. This is very useful for CheckBoxes and Radio Buttons.

<!-- Standard HTML4.1 -->
<input type="checkbox" id="CHKCandies" value="1" />
<label for="CHKCandies">I want some candies</label>

In .Net you can always assign some text to a CheckBox or Radio Button using its Text property, but, in case you want to add some functionality to that text like a link in the typical “[ ] I’m agree with the <a>Terms of use</a>” or similar you may find that the Text property in a Radio Button isn’t enough.

Fortunately the Label control not only has a Text attibute but also acts as a container letting you write anything between its tags. So, you can add more lines of text, links and other labels inside it. Once done, to assign it to an input control you can use the property AssociatedControlID, the label will now be linked with that control and your Radio Buttons and CheckBoxes will be checked/unchecked when you click the associated text, making them easier to use.

//Example 1:
<asp:Label ID="lbTermsUse" runat="server" AssociatedControlID="CHKTerms">
   I agree to 
   <a href="TermsAndConditions.aspx" target="_blank">terms and conditions</a>
   <span class="highlight">*</span>
</asp:Label>
<asp:CheckBox ID="CHKTerms" runat="server" class="required" />

//Example 2:
<div class="option">
   <asp:RadioButton runat="server" GroupName="EmergencyCl" ID="eOneYear" AutoPostBack="true"
      OnCheckedChanged="eOneYear_CheckedChanged" />
   <asp:Label ID="Label4" runat="server" Text="" AssociatedControlID="eOneYear">
      One year service for <br />&pound;<asp:Label ID="e12Months" runat="server"></asp:Label> per month
   </asp:Label>
</div>
<div class="option">
   <asp:RadioButton runat="server" GroupName="EmergencyCl" ID="eTwoYear" AutoPostBack="true"
      OnCheckedChanged="eTwoYear_CheckedChanged" />
   <asp:Label ID="Label5" runat="server" Text="" AssociatedControlID="eTwoYear">
      Two years service for <br />&pound;<asp:Label ID="e24Months" runat="server"></asp:Label> per month
   </asp:Label>
</div>

Leave a Reply

Close Bitnami banner
Bitnami