tags:

views:

65

answers:

5

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?

+1  A: 

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;
}
Darkxes
What if the parent is not a panel?
BrunoLM
That is gonna get the top parent Panel only. I mean it's not gonna blow up, it will just give you the top parent panel that you have.
Darkxes
A: 
bool isChildofParent = false;  
 foreach (Control ctl in ParentPanel.Controls)  
 {  
   if (ctl.Controls.Contains(P))  
   {  
     isChildofParent = true;  
     break;  
   }  
 }  
Kamyar
This is not a recursive solution, it´ll get only the first set of controls.
Augusto Radtke
This is not recursive because As mentioned by the post author, He has **3** panels. this is a specific solution to his problem. it's simple and it works.
Kamyar
A: 

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)

James Connell
A: 

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));
}
y34h
+5  A: 

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
BrunoLM
Love it man ... I think that is the best solution you could have!
Darkxes