BrunoLM
BrunoLM

Reputation: 100341

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

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

Answers (5)

Kamyar
Kamyar

Reputation: 18797

bool isChildofParent = false;  
foreach (Control ctl in ParentPanel.Controls)  
{  
   if (ctl.Controls.Contains(P))  
   {  
      isChildofParent = true;  
      break;  
   }  
}  

Upvotes: 0

BrunoLM
BrunoLM

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

y34h
y34h

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

automagic
automagic

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

pjnovas
pjnovas

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

Related Questions