February 11, 2009

TIP: How to use form labels with ASP.NET controls


You want to use <label> to point to fields in your ASP.NET controls, but due to HTML ID mangling, you cannot.


Walk the control tree on load and update the "for" attribute on the <label>.

For example, let's say you have the following code in your control:

<label for="UserName">User Name</label>
<asp:textbox id="UserName" runat="server" columns="30">

First, add runat="server" and an ID to your <label> like so:

<label ID="UserNameLabel" for="UserName" runat="server">
User Name</label>
<asp:textbox id="UserName" runat="server" columns="30">

The ID keeps Visual Studio happy.

Then, in your Page_Load(), call the following helper function:

private void UpdateLabelsWithClientID(Control c)
foreach (Control c1 in c.Controls) UpdateLabelsWithClientID(c1);
if (c is HtmlGenericControl && ((HtmlGenericControl)c).TagName == "label")
string controlName = ((HtmlGenericControl)c).Attributes["for"];
Control c2 = this.FindControl(controlName);
if (c2 != null) ((HtmlGenericControl)c).Attributes["for"] = c2.ClientID;

If you are in an ASP.NET control, you would call it as UpdateLabelsWithClientID(this);.

1 comment:

Sarkie said...

Done near enough the same code. But with dotnetnuke, it was even worse! :)

Thanks tho.