C# 正在努力摆脱递归Page.FindControl

C# 正在努力摆脱递归Page.FindControl,c#,C#,我开发了一个web仪表板,它有一个嵌入控件内部的控件结构。在许多情况下,我有控件的ID,需要处理实际的控件对象。同样地,我使用一个实用方法,一个递归FindControl实现,它搜索Page(或任何其他提供的对象,但我总是使用Page)以获得控件的ID /// <summary> /// Page.FindControl is not recursive by default. /// </summary> /// <param name="root"> Pa

我开发了一个web仪表板,它有一个嵌入控件内部的控件结构。在许多情况下,我有控件的ID,需要处理实际的控件对象。同样地,我使用一个实用方法,一个递归FindControl实现,它搜索Page(或任何其他提供的对象,但我总是使用Page)以获得控件的ID

/// <summary>
/// Page.FindControl is not recursive by default.
/// </summary>
/// <param name="root"> Page </param>
/// <param name="id"> ID of control looking for. </param>
/// <returns> The control if found, else null. </returns>
public static Control FindControlRecursive(Control root, string id)
{
    if (int.Equals(root.ID, id))
    {
        return root;
    }

    foreach (Control control in root.Controls)
    {
        Control foundControl = FindControlRecursive(control, id);

        if (!object.Equals(foundControl,null))
        {
            return foundControl;
        }
    }

    return null;
}
无法保证此控件将是页面的直接子控件,而且我(据我所知!)无法确定此ID在控件中的位置,除非从页面向下搜索

我唯一能想到的就是为页面上的每个对象保留一个查找表,但这似乎是错误的想法


还有其他人遇到过这个问题吗?

Hrm,这个怎么样。。。HtmlElementID应该是控件的客户端ID,它应该是控件的完全限定位置

/// <summary>
/// Page.FindControl is not recursive by default.
/// </summary>
/// <param name="root"> Page </param>
/// <param name="id"> ID of control looking for. </param>
/// <returns> The control if found, else null. </returns>
public static Control FindControlRecursive(Control root, string id)
{
    if (int.Equals(root.ID, id))
    {
        return root;
    }

    foreach (Control control in root.Controls)
    {
        Control foundControl = FindControlRecursive(control, id);

        if (!object.Equals(foundControl,null))
        {
            return foundControl;
        }
    }

    return null;
}
大概是这样的:

protected void RadListBox_Dropped(object sender, RadListBoxDroppedEventArgs e)
{
    //e.HtmlElementID is the UniqueID of the control I want to work upon.
    RadDockZone activeControlDockZone = Utilities.FindControlRecursive(Page, e.HtmlElementID) as RadDockZone;
}
页面\u父级\u 0\u控件\u 1

您可以拆分ID字符串,然后通过拼凑到该控件的路径,从页面向下导航到该控件

Page findcontrol Page#u父级(索引#0) Page_Parent_0 findcontrol Page_Parent_0_控件(索引#1)

这仍然不是最好的方法,但它可以避免你用散弹枪搜索有问题的控制装置


希望这会对你起作用,或者至少给你另一种看待问题的方式:

你考虑或查看VIEWSTATE吗?希望找到一个在MVC框架下支持的解决方案。在最后一次重构之后,我将尝试将这个项目转换为那个项目。据我所知,MVC不支持ViewState——将我的ASP.NET Page.FindControl视为ViewPage.FindControl方法是否可以接受?我会经历同样的缓慢吗?这绝对是一件值得考虑的事情。我会让它开放一段时间,但如果没有出现任何问题,我会看看你提出的解决方案的好处!