在jQuery中有一個叫做.parents('xx')的很酷的函數,它使我可以從DOM樹中的某個對象開始,向上搜索DOM以找到特定類型的父對象。C#相當於jQuery.parents(類型)
現在我在C#代碼中尋找同樣的東西。我有一個asp.net panel
有時坐在另一個家長面板,有時甚至2或3家長面板,我需要向上旅行通過這些父母終於找到UserControl
,我正在尋找。
有沒有一種簡單的方法在C#/ asp.net中做到這一點?
在jQuery中有一個叫做.parents('xx')的很酷的函數,它使我可以從DOM樹中的某個對象開始,向上搜索DOM以找到特定類型的父對象。C#相當於jQuery.parents(類型)
現在我在C#代碼中尋找同樣的東西。我有一個asp.net panel
有時坐在另一個家長面板,有時甚至2或3家長面板,我需要向上旅行通過這些父母終於找到UserControl
,我正在尋找。
有沒有一種簡單的方法在C#/ asp.net中做到這一點?
編輯:重讀你的問題後,我曾根據帖子中的第二個鏈接它刺傷:
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創建一個更好的版本。
這不是周圍的錯誤的方式? OP要求向上搜索,但這是向下搜索,如果我沒有錯。 – ChrisWue 2012-04-15 21:59:56
是的你是對的,但是這應該把他/她放在正確的路線上。 – 2012-04-15 22:01:27
更新了一個實驗實現。 – 2012-04-15 22:08:54