C#相当于jQuery.parents(Type)

Tys*_*Tys 5 c# asp.net

在jQuery中有一个叫.家长("XX")很酷的功能,使我开始的地方与对象在DOM树和DOM向上搜索,寻找特定类型的父对象.

现在我在C#代码中寻找相同的东西.我有一个asp.net panel有时坐在另一个父母小组,或有时甚至2或3个父母小组,我需要通过这些父母向上旅行,最终找到UserControl我正在寻找的.

在C#/ asp.net中有一个简单的方法吗?

Rob*_*ett 2

编辑:重读您的问题后,我根据帖子中的第二个链接进行了尝试:

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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,未经测试,现在刚刚完成。

以下供参考。

有一个名为 FindControlRecursive 的常用函数,您可以在其中从页面向下遍历控件树以查找具有特定 ID 的控件。

这是来自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; 
}
Run Code Online (Sandbox Code Playgroud)

你可以这样使用:

var control = FindControlRecursive(MyPanel.Page,"controlId");
Run Code Online (Sandbox Code Playgroud)

您还可以将其与以下内容结合起来:http ://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx创建一个更好的版本。