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

1

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 descending from ParentPanel ?

    
asked by anonymous 22.12.2013 / 01:40

1 answer

1

You can use a extension method recursive like this :

public static bool IsChildOf(this Control c, Control parent)
{
    return ((c.Parent != null && c.Parent == parent)
            || (c.Parent != null ? c.Parent.IsChildOf(parent) : false));
}

What results in:

P.IsChildOf(ParentPanel); // true
ParentPanel.IsChildOf(P); // false
    
22.12.2013 / 01:40