努力摆脱递归的Page.FindControl

Sea*_*son 6 c#

我开发了一个Web控制面板,其中包含嵌入控件内部的控件结构.在许多情况下,我有一个控件的ID,需要处理实际的控件对象.因此,我使用一个实用方法,一个递归的FindControl实现,它搜索页面(或任何其他提供的对象,但我总是使用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;
}
Run Code Online (Sandbox Code Playgroud)

此功能可以变得非常慢.一旦我把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;
}
Run Code Online (Sandbox Code Playgroud)

不能保证这个控件将是Page的直接子节点,我不知道(据我所知!),除了通过向下搜索页面之外,我能够确定控件中ID的位置.

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

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

Cra*_*igW 2

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

像这样的东西:

Page_Parent_0_Control_1

您可以分解 ID 字符串,然后通过拼凑路径从页面向下导航到相关控件。

页面查找控件 Page_Parent(索引 #0) Page_Parent_0 查找控件 Page_Parent_0_Control(索引 #1)

仍然不是最好的方法,但它可以让您免于对有问题的控件进行霰弹式搜索。

希望这对您有用,或者至少为您提供另一种看待问题的方式:)