Finding Web Controls by Type

If someone runs into the same problem I was having which was trying to find controls of a certain type they can use this extension method which extends the Control object:

public static class ControlExtensions
{
    public static ICollection FindControlsByType(this Control control)
        where T : Control
    {
        var coll = new List();
        if (control == null) return coll;

        FindControlsByType(control.Controls, coll);
        return coll;
    }

    private static void FindControlsByType(ControlCollection controls, ICollection coll)
        where T : Control
    {
        foreach (Control current in controls)
        {
            if (current.HasControls())
                FindControlsByType(current.Controls, coll);

            if (current is T)
                coll.Add(current as T);
        }
    }
}

Remember as with all extension methods if you are using them in an inherited class you will need to put this before the name of the method otherwise it won’t be seen in intellisense.

Advertisements