Reputation: 89
Easy one here.
I have a control inside a control inside a masterpage. The page name looks something like this in HTML
ctl00$MasterPageBody$MainControl$ChildControl
Any idea how I can get the above from code behind?
Thanks!
Upvotes: 0
Views: 119
Reputation: 2872
You should use a function similar to this:
public static Control FindControlRecursive(Control ctl, string id) {
if (!ctl.HasControls())
return null;
Control res = null;
foreach(Control c in ctl.Controls) {
if (c.ID == id) {
res = c;
break;
} else {
res = FindControlRecursive(c, id);
if (res != null)
break;
}
}
return res;
}
in this way:
Control ChildControl = FindControlRecursive(this.Page, "ChildControl");
string ID = ChildControl.ClientID;
Upvotes: 0
Reputation: 13286
If we're talking about a top-level control on the page, or at least one that isn't in any sort of repeating type, you can just use the ClientID
property.
<asp:Label runat="server" ID="testLabel" />
<script>
$('#<%= testLabel.ClientID %>').click(function() { ... });
</script>
If we're talking about something that isn't accessible directly like that, you'll have to do the same thing, but it'll have to be wrapped in a FindControl
. The example of that isn't so clean, so I'll trust you can understand from my words. But basically, if you have a label that shows code-behind-given text on each row of a GridView
, you'll have to call ((Label)e.Row.FindControl("testLabel")).ClientID
. Still pretty straight-forward, but a bit more complicated than the first case.
Upvotes: 1