February 19, 2009

Duh.

It's always nice when you spend time reinventing the wheel when you don't need to.

For example, take my recent post on associating a label to an ASP.NET mangled control name.

Turns out the functionality is built into ASP.NET.

Let's say you have the following ASP.NET code...

<asp:label runat="server" text="Search" /><asp:textbox id="query" runat="server" />

...and you want to link the Label to the TextBox. Set the AssociatedControlID property on the Label and it will automatically handle mangled control names for you.

<asp:label runat="server" text="Search" AssociatedControlID="query" /><asp:textbox id="query" runat="server" />

I'm still going to leave up my original post because knowing how to recursively work with HtmlControls is a good thing, but I hate it when I miss something this obvious.

2 comments:

ThomW said...

Speaking of "reinventing the wheel" it bugs me that much of ASP.NET seems like a giant wheel reinvention itself.

Look at AssociatedControlID -- why isn't it just implemented as "for" like in normal HTML?

Michael Russell said...

Because not all browsers support the same tag set and asp:Label is not the same as the HTML label.

asp:Label is a generic placeholder for plain text content. ASP.NET spits out special tags depending on the properties set on the control. Have special formatting? A span with inline style. Have an associated control ID? On some browsers, a label tag with a for. On some mobile browsers, a tag more appropriate.