簡體   English   中英

C#查找控件

[英]C# Find Control

我試圖訪問一個輔助類文件的控制和我似乎無法找到控制。

背后的代碼:

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

為什么我不能從其他類文件引用控件。 注意:它不是頁面的部分類。 我將這個幫助器類用於25個不同的頁面。

FindControl已不查找嵌套控制。 這是一個遞歸的查找控件,應歸功於編碼恐怖

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

不幸的是, FindControl找不到嵌套控件。 從MSDN:

僅當控件直接包含在指定的容器中時,此方法才會找到該控件; 也就是說,該方法不會在控件內的整個控件層次結構中進行搜索。

例:

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

在上一個示例中,如果您查找Label, FindControl將找不到它。 相反,如果您查找面板,它將找到它。

更多信息在這里:

Control.FindControl方法(字符串)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM