Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent of jQuery.parents(Type)

Tags:

c#

asp.net

In jQuery there is a cool function called .parents('xx') that enables me to start with an object somewhere in the DOM tree and the search upwards in the DOM to find a parent object of a specific type.

Now i'm looking for the same thing within C# code. I have an asp.net panel which sometimes sits in another parent panel, or sometimes even 2 or 3 parent panels and i need to travel upwards through these parents to finally find the UserControl that i'm looking for.

Is there an easy way to do this in C# / asp.net?

like image 650
Tys Avatar asked Oct 08 '22 02:10

Tys


1 Answers

Edit: after rereading your question, I had a stab at it based on the second link in my post:

public static T FindControl<T>(System.Web.UI.Control Control) where T : class
{
     T found = default(T);

     if (Control != null && Control.Parent != null)
     {
        if(Control.Parent is T)
            found = Control.Parent;
        else
            found = FindControl<T>(Control.Parent);
     }

     return found;
}

Please note, untested, just made this up now.

Below for reference.

There's a common function called FindControlRecursive where you can walk the control tree from the page down to find a control with a specific ID.

Here's an implementation from http://dotnetslackers.com/Community/forums/find-control-recursive/p/2708/29464.aspx

private Control FindControlRecursive(Control root, string id) 
{ 
    if (root.ID == id)
    { 
        return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
        Control t = FindControlRecursive(c, id); 
        if (t != null) 
        { 
            return t; 
        } 
    } 

    return null; 
}

You could use this like:

var control = FindControlRecursive(MyPanel.Page,"controlId");

You could also combine it with this: http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx to create a nicer version.

like image 61
Rob Stevenson-Leggett Avatar answered Oct 13 '22 11:10

Rob Stevenson-Leggett