[英]Find control by id in a UserControl structure
情況 (不是麥克):
我有許多UserControls,它是從一個父級繼承的。
在父Page_Load
,我想從子UserControl中找到一個特定的控件,並為其添加Attributes
。
問題是我永遠不知道子UserControl
的結構。
我試圖使用遞歸方法通過id查找控件:
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
這就是我從父母那里稱呼它的方式:
Page page = HttpContext.Current.Handler as Page;
var mycontrol = FindControlRecursive(page, "id_x");
if (mycontrol != null)
{
string test = "";
}
但是我不工作。 我真的不確定這是否是實現我的目標的好方法。 請,我想知道您是否有任何建議或更好的方法。 非常感謝您的幫助。
如下更改您的查找方法
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
foreach (Control control in root.Controls)
{
Control found = RecursiveFindControl(control, id);
if (found != null)
return found;
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.