C# – Accessing a Label from a Textbox through AssociatedControlID

asp.netc

If I have a label and a textbox and a label

<asp:Label ID="Label1" runat="server" Text="Name" AssociatedControlID="txtName"></asp:Label>
<asp:TextBox ID="txtName" runat="server" CssClass="textbox"></asp:TextBox>

From code-behind, is it posible to access the controls that list the Textbox as an associated control.

Best Answer

It's possible, but probably not as easy as you'd like. There is no collection anywhere that says "these are all the controls with this AssociatedControlID value". You would need to loop over all the controls in the page recursively and check the AssociatedControlID property if it's a label.

What are you trying to accomplish? I know you specifically asked about doing it code-behind, but if the end result is that you're trying to manipulate the UI, I would consider using jQuery, as with a single line of javascript you would be able to select all the elements on the page that had for = "txtName".