by Rusty Swayne 10.March 2008 13:19
It amazes how much functionality Microsoft builds into its' simplest of controls and the fact that you can use them for years and still be discovering things you might have overlooked. For the past few years I had been stewing over the fact that there was no obvious way to create the simple label for a form element with the 'for' attribute set to target the ever changing id of some control on the page. In a few cases, where I thought it to be important, I have even written recursive lookups, searching through every control within a page to find the generated clientid to accomplish this. Only now I know I missed the obvious and the asp.net label control is just sitting out there with this functionality able and waiting, the AssociateControlID property.
To my credit, most developers don't seem to care so much about sending symantic HTML markup to the response and tend to use the asp.net label control in situations where asp.net literal control is probably the more appropriate choice. This is really propagated in many of the example code snippets one can find in manuals, books and online and greatly contributes to its' misuse.
In most cases published examples are something like:
Username <asp:textbox id="txtUsername" runat="server" />
Until now, in my attempt to generate semantic markup, I have at least used:
<label title="Username">Username <asp:textbox id="txtUsername" ruant="Server" /></label>
The fact that I overlooked fact that the asp.net label control contains the property AssociateControlID the new construct will always be as follows:
<asp:label associatecontrolid="txtUsername" runat="server" id="lblUsername" title="Username">Username: <asp:textbox id="txtUsername" runat="server" /></label>
This will add the beloved 'for' attribute for the label, add the functionality that when the label is clicked the textbox gets the focus and makes the form element construct more accessible in general.
It would be so great to be able to keep tabs on everything!