努力摆脱递归Page.FindControl

问题描述

|| 我已经开发了一个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;
}
功能有可能变得很慢。我知道一旦将log4net记录到日志中,它就会变得多么缓慢。我现在正尽力摆脱它,但我不确定我还有其他选择。 例如,用户将控件拖放到我的网页上。事件处理程序如下所示:
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;
}
无法保证此控件将是Page的直接子对象,并且我(据我所知!)没有能力确定该ID在控件中的位置,除非从Page向下搜索。 我唯一能想到的就是在Page上保留每个对象的查找表,但这似乎是一个错误的主意。 还有其他人遇到过这个问题吗?     

解决方法

        Hrm,如何处理……HtmlElementID应该是控件的客户端ID,希望它应该是控件的完全限定位置。 像这样: Page_Parent_0_Control_1 您可以分解ID字符串,然后通过将其路径拼凑在一起而从页面向下导航至相关控件。 页面findcontrol Page_Parent(索引#0) Page_Parent_0 findcontrol Page_Parent_0_Control(索引1) 仍然不是最好的方法,但是它将避免您用a弹枪搜索相关控件。 希望这对您有用,或者至少给您另一种解决问题的方法:)