Reputation: 45669
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.
Upvotes: 2
Views: 1921
Reputation: 116977
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"
.
Upvotes: 3
Reputation: 7299
You can do it using LINQ.
var label = Page.Controls
.Cast<Control>()
.SingleOrDefault(c => c.GetType() == typeof(Label) &&
((Label)c).AssociatedControlID == "txtName");
If you have multiple controls associated with that particular textbox, then use Where()
instead of SingleOrDefault()
.
Upvotes: 0