【问题标题】:FindControl getting wrong control in my recursive methodFindControl 在我的递归方法中得到错误的控制
【发布时间】:2011-03-12 08:41:00
【问题描述】:

我使用以下方法递归查找asp.net页面上的控件:

    /// <summary>
    /// Searches recursively for a server control with the specified id parameter.
    /// </summary>
    /// <param name="start">The start.</param>
    /// <param name="id">The id.</param>
    /// <returns>A <see cref="Control"/></returns>
    public static Control FindControl(Control start, string id)
    {

        Control foundControl;
        if (start == null)
            return null;

        foundControl = start.FindControl(id);
        if (foundControl != null)
            return foundControl;

        foreach (Control c in start.Controls)
        {
            foundControl = FindControl(c, id);
            if (foundControl != null)
                return foundControl;
        }

        return null;
    }

我遇到了一个问题,因为它返回了错误的控件。我将问题追溯到标准的 FindControl 方法,并通过检查返回的控件的 id 确实与请求的匹配来修复它,如下所示:

    foundControl = start.FindControl(id);
        if (foundControl != null && foundControl.ID == id)
            return foundControl;

我的问题是为什么 start.FindControl(id) 返回的控件与请求的 id 不匹配?

【问题讨论】:

    标签: asp.net web-controls


    【解决方案1】:

    我用

    static class ControlExtension
        {
            public static IEnumerable<Control> GetAllControls(this Control parent)
            {
                foreach (Control control in parent.Controls)
                {
                    yield return control;
                    foreach (Control descendant in control.GetAllControls())
                    {
                        yield return descendant;
                    }
                }
            }
        }
    

    然后打电话

    var foundControl =  Page.GetAllControls().Where(c => c.ID = id);
    

    编辑:

    也许不是调用它来开始搜索

     foundControl = start.FindControl(id);
    

    你应该从

    开始
    foundControl = FindControl(start, id);
    

    【讨论】:

    • 是的,根本不使用 FindControl,看起来很强大,可以根据我喜欢的任何标准查找控件。不幸的是,我被困在一个不想升级到 C#3.0 的地方,所以还没有 lambda 表达式......我仍然可以在 C#2.0 中重写我的方法,只检查 ID 是否匹配而不使用 FindControl,但我很好奇 FindControl 是如何返回一个与参数指定的 ID 明显不匹配的控件。
    • 重新编辑。我需要foundControl = start.FindControl(id);或其他一些识别正确控件的方法,否则它将始终为空。
    • 我可以重写它来比较循环内的 id,即 if (c.id == id) return c;我真的只是对 FindControl 的意外行为感到好奇,并想知道是否有其他人遇到过这个问题
    猜你喜欢
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多