Geeks With Blogs
Dennis Ecclestone's BLOG

For accessibility reasons, it’s recommended that you use the <label> tag rather than than the ASP.NET label server control.  As an example; 

<label for="AssemblyItems">Assembly Serial Number</label><br>

<asp:listbox id="AssemblyItems" runat="server" cssclass="listbox" selectionmode="Multiple" rows="15" enableviewstate="False"></asp:listbox><br>

The advantage to this is that it can be read by an aural screen reader.  As well, when you click on the label, the associated control will be selected. 

This is all well and good if you put the <label> tag directly on a Web form.  However, if it’contained inside an ASP.NET user control then it won’t work as expected.  The problem is that the HTML gets rendered as follows;

<label for="AssemblyItems">Assembly Serial Number</label><br><select name="CM:AssemblyItems" size="15" multiple="multiple" id="CM_AssemblyItems" class="listbox">

The issue here is that the ID of the listbox doesn’t match the value specified in the “for” attribute of the <label> tag.  The solution to this problem is really quite straight forward.  We just need to convert the <label> into a server-side control and use data-binding to set the value of the “for” attribute. 

The code for the <label> tag is as follows;

 

<label id="AssemblyItemsLabel" runat="server" for='<%# Me.AssemblyItems.ClientId %>'>Assembly Serial Number</label><br>

<asp:listbox id="AssemblyItems" runat="server" cssclass="listbox" selectionmode="Multiple" rows="15" enableviewstate="False"></asp:listbox><br>

 

 Then add a reference for the label and add the code to Page_Init to data-bind the label.

 

        Protected WithEvents AssemblyItemsLabel As System.Web.UI.HtmlControls.HtmlGenericControl

         Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init

            'CODEGEN: This method call is required by the Web Form Designer

            'Do not modify it using the code editor.

            InitializeComponent()

 

            ' Populate the AssemblyItems ListBox with all of the assembly items.  The ViewState of the ListBox

            ' is disabled so it must be populated on each PostBack.

            BindAssemblyItems()

            Me.AssemblyItemsLabel.DataBind()

        End Sub

 Now the HTML will get rendered correctly as follows…

<label id="CM_AssemblyItemsLabel" for="CM_AssemblyItems">Assembly Serial Number</label><br><select name="CM:AssemblyItems" size="15" multiple="multiple" id="CM_AssemblyItems" class="listbox">

Posted on Friday, March 17, 2006 10:54 AM | Back to top


Comments on this post: Using a Label tag inside of ASP.NET User Controls

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Dennis Ecclestone | Powered by: GeeksWithBlogs.net