Colin
Colin

Reputation: 22595

FindControl getting wrong control in my recursive method

I use the following method to find a control on an asp.net page recursively:

    /// <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;
    }

I hit a problem because it was returning the wrong control. I tracked the problem down to the standard FindControl method, and fixed it by checking that the id of the control returned did actually match the one requested like this:

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

My question is why does start.FindControl(id) ever return a control that does not match the id requested?

Upvotes: 1

Views: 481

Answers (1)

Bala R
Bala R

Reputation: 108997

I use

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;
                }
            }
        }
    }

and call

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

EDIT:

maybe instead of calling this to start the search

 foundControl = start.FindControl(id);

you should start with

foundControl = FindControl(start, id);

Upvotes: 2

Related Questions