Achieving user friendly Labels with .NET
Making your forms as user friendly as possible is something we all strive for and one common technique is to make our form labels clickable – focusing on the relevant input field upon click.
This can easily be achieved by using the for attribute:
<label for="inputSample">Label</label> <input type="text" id="inputSample" />
Simple enough when coding with HTML, but with .NET Controls, it requires a bit more knowledge in achieving the same effect. From my own experience, you will come across the following problems:
- When using the
forattribute, you need to know the ID of the relevant input. With .NET, the ID renders differently depending on the namspace of the page, whether is in a master page or user control. For example, if I were to give an input field the ID “inputSample”, this would render something a long the lines of “ct100_inputSample”, or within a user control “ct100_usercontrolName_inputSample”. So as you can see, ID’s in .NET aren’t as straight forward. - Straight out of the box, the
asp:labeltag renders as aspanon the page rather than thelabelwe were hoping for. Which doesn’t really help when it comes to styling the form with CSS.
Therefore, in order to match the ID of the input and to render the tag as a label, we would use the AssociatedControlID attribute. By giving this attribute the same value as the input ID, the label’s for value and input ID value would match up. The asp:label tag also now renders as a label.
<asp:Label id="lblSample" runat="server" text="Label Text" AssociatedControlID="txtSample" /> <asp:Textbox id="txtSample" runat="server" />
For added effect, apply a CSS style of cursor: pointer to the label so the user realises these fields are clickable.