2012-04-15 97 views
5

在jQuery中有一个叫做.parents('xx')的很酷的函数,它使我可以从DOM树中的某个对象开始,向上搜索DOM以找到特定类型的父对象。C#相当于jQuery.parents(类型)

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

有没有一种简单的方法在C#/ asp.net中做到这一点?

回答

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; 
} 

请注意,未经检验的,只是做这件事了。

以下仅供参考。

有一个称为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; 
} 

实现您可以使用此类似:

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

你也可以用这个结合起来:http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx创建一个更好的版本。

+0

这不是周围的错误的方式? OP要求向上搜索,但这是向下搜索,如果我没有错。 – ChrisWue 2012-04-15 21:59:56

+0

是的你是对的,但是这应该把他/她放在正确的路线上。 – 2012-04-15 22:01:27

+0

更新了一个实验实现。 – 2012-04-15 22:08:54

2

您应该能够使用ControlParent属性:

private Control FindParent(Control child, string id) 
{ 
    if (child.ID == id) 
     return child; 
    if (child.Parent != null) 
     return FindParent(child.Parent, id); 
    return null; 
}