努力摆脱递归的Page.FindControl

时间:2011-06-14 18:13:33

标签: c#

我开发了一个网络仪表板,其中嵌入了控件内部的控件结构。在许多情况下,我有一个控件的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的直接子节点,而我(据我所知!),我无法确定此控件在此控件中的位置,除非从向下搜索页面。

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

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

1 个答案:

答案 0 :(得分:2)

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

这样的事情:

Page_Parent_0_Control_1

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

Page findcontrol Page_Parent(index#0) Page_Parent_0 findcontrol Page_Parent_0_Control(index#1)

仍然不是最好的方法,但它可以帮助您避免对相关控件进行霰弹枪搜索。

希望这对你有用,或至少给你另一种看待问题的方法:)

相关问题