Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a control is child of another control? "Control.IsChildOf"

Tags:

c#

asp.net

linq

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?

like image 837
BrunoLM Avatar asked Oct 08 '10 17:10

BrunoLM


2 Answers

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
like image 131
BrunoLM Avatar answered Nov 14 '22 22:11

BrunoLM


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;
}
like image 34
pjnovas Avatar answered Nov 14 '22 22:11

pjnovas