Finding all controls in an ASP.NET Panel?

It boils down to enumerating all the controls in the control hierarchy:

    IEnumerable<Control> EnumerateControlsRecursive(Control parent)
    {
        foreach (Control child in parent.Controls)
        {
            yield return child;
            foreach (Control descendant in EnumerateControlsRecursive(child))
                yield return descendant;
        }
    }

You can use it like this:

        foreach (Control c in EnumerateControlsRecursive(Page))
        {
            if(c is TextBox)
            {
                // do something useful
            }
        }

Leave a Comment