C# 查找控件

C# Find Control

我正在尝试访问助手 class 文件上的控件,但我似乎找不到该控件。

隐藏代码:

protected void Page_Load(object sender, EventArgs e)
{
    FoxHelper p = new FoxHelper();

    //  load page
    p.loadFoxPage(this.Page);
}

助手类:

public void loadFoxPage(Page thePage)
{
    //  set the master page
    m = (SiteN)thePage.Master;

    HtmlGenericControl ctrl = (HtmlGenericControl)thePage.FindControl("ADMMgM");
}

为什么我不能引用其他 class 文件中的控件。注意:它不是页面的部分 class。我将此助手 class 用于 25 个不同的页面。

很遗憾,FindControl 找不到嵌套控件。来自 MSDN:

This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls.

示例:

<asp:Panel ID="pnl" runat="server">
    <asp:Label ID="lbl" runat="server" Text="I'm here!" />
</asp:Panel>

在前面的示例中,如果您查找标签,FindControl 将找不到它。相反,如果您查找面板,它会找到它。

更多信息在这里:

Control.FindControl Method (String)

FindControl 不查找嵌套控件。这是一个递归查找控件,归功于 coding horror

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