Sometimes you want to work with all controls on an ASP.NET page by type rather than id. I finally got fed up with the lack of builtin support, and wrote the following method that returns all controls inside another control (or page) by type:

public List<T> FindControls<T>(Control parent) where <T> : Control
{
    List<T> foundControls = new List<T>();

    FindControls<T>(parent, foundControls);

    return foundControls;
}

void FindControls<T>(Control parent, List<T> foundControls) where <T> : Control
{
    foreach (Control c in parent.Controls)
    {
        if (c is <T>)
            foundControls.Add((<T>)c);
        else if (c.Controls.Count > 0)
            FindControls<T>(parent, foundControls);                
    }
}

Comments

Comment by Arsi

Thanks, that helped me a lot! :)

Arsi
Comment by Eric Chau

Your code has inspired me to create a utility class that does exactly as shown. However, I have found some errors in the code. The cleaned up version is as follows. Cheers.

public class ControlUtility
{
public static List<T> FindControls<T>(Control parent) where T : Control
{


List<T> foundControls = new List<T>();

FindControls<T>(parent, foundControls);

return foundControls;
}


static void FindControls<T>(Control parent, List<T> foundControls) where T : Control
{
foreach (Control c in parent.Controls)
{
if (c is T)
foundControls.Add((T)c);
else if (c.Controls.Count > 0)
FindControls<T>(c, foundControls);
}
}
}

Eric Chau
Comment by David Brown

I tried converting to vb.net, unable to do so. Would you have this in VB.net? If so please forward.

thanks

David Brown
Comment by Mendy

Public Function FindControls(Of T) where (Of T) : Control(ByVal parent As Control) As List(Of T)
Dim foundControls As List(Of T) = New List(Of T)()

FindControls(Of T)(parent, foundControls)

Return foundControls
End Function

Private Sub FindControls(Of T) where (Of T) : Control(ByVal parent As Control, ByVal foundControls As List(Of T))
For Each c As Control In parent.Controls
If TypeOf c Is (Of T) Then
foundControls.Add(CType(c, (Of T)))
ElseIf c.Controls.Count > 0 Then
FindControls(Of T)(parent, foundControls)
End If
Next c
End Sub

Mendy
Comment by Richard Collette

The VB version wasn't quite VB and does some extra type casting. Here is some updated VB code (sorry the formatting isn't preserved.

Public Function FindControls(Of T As Control)(ByVal parent As Control) As List(Of T)
Dim foundControls As List(Of T) = New List(Of T)()
FindControls(Of T)(parent, foundControls)
Return foundControls
End Function

Public Sub FindControls(Of T As Control)(ByVal parent As Control, ByVal foundControls As List(Of T))
For Each c As Control In parent.Controls
Dim cOfT As T = TryCast(c, T)
If cOfT IsNot Nothing Then
foundControls.Add(cOfT)
ElseIf c.Controls.Count > 0 Then
FindControls(Of T)(parent, foundControls)
End If
Next c
End Sub

Richard Collette