使用FindControl("")的简便方法

Wil*_*Dud 8 c# asp.net

C#

嗨,

我已经开发了几年的c#web应用程序,并且有一个问题我不断发现我无法找到合理的解决方法.

我有一个控件我想在后面的代码中访问,这个控件在标记内深处; 在ContentPlaceHolders,UpdatePanels,Panels,GridViews,EmptyDataTemplates,TableCells(或任何你喜欢的结构)中埋葬......关键是它有更多的父母而不是更多的父母.

如何FindControl("")在不执行此操作的情况下使用访问此控件:

Page.Form.Controls[1].Controls[1].Controls[4].Controls[1].Controls[13].Controls[1].Controls[0].Controls[0].Controls[4].FindControl("");
Run Code Online (Sandbox Code Playgroud)

Rob*_*Day 12

编写一个名为FindControlRecursive的辅助方法,由Jeff Atwood自己提供.

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)

递归Page.FindControl