Reputation: 100341
I have 3 panels:
<asp:Panel ID="ParentPanel" runat="server">
<asp:Panel ID="AnnoyingPanel" runat="server">
<asp:Panel ID="P" runat="server">
</asp:Panel>
</asp:Panel>
</asp:Panel>
How can I check if P
is child of ParentPanel
? Is there some LINQish way to do it?
Is there some more optimized way than the one I provided? Maybe using Linq?
Upvotes: 6
Views: 3983
Reputation: 18797
bool isChildofParent = false;
foreach (Control ctl in ParentPanel.Controls)
{
if (ctl.Controls.Contains(P))
{
isChildofParent = true;
break;
}
}
Upvotes: 0
Reputation: 100341
I end up making a recursive extension method
public static bool IsChildOf(this Control c, Control parent)
{
return ((c.Parent != null && c.Parent == parent) || (c.Parent != null ? c.Parent.IsChildOf(parent) : false));
}
Resulting in
P.IsChildOf(ParentPanel); // true
ParentPanel.IsChildOf(P); // false
Upvotes: 10
Reputation: 1659
i haven't tested this, but should work:
bool IsParent(Control child, Control parent)
{
return child.CliendID.StartsWith(parent.ClientID);
}
unless you have ClientIDMode = Static
EDIT: this one work even id you set the ClientIDMode
bool IsParent(Control child, Control parent)
{
return child.NamingContainer != null && (child.NamingContainer == parent || IsParent(child.NamingContainer, parent));
}
Upvotes: 0
Reputation: 1077
maybe something like:
var p = Page.FindControl("ParentPanel") as Panel;
var res = p.Controls.AsQueryable().OfType<Panel>().Any(x => x.ID == "P");
(disclaimer: not tested)
Upvotes: 0
Reputation: 1116
You can do that search recursive:
Panel topParent = GetTopParent(P);
private Panel GetTopParent(Panel child)
{
if (child.Parent.GetType() == typeof(Panel))
return GetTopParent((Panel)child.Parent);
else return child;
}
Upvotes: 1