Krystalware
Products | Purchase | Free Stuff | Forums | Blog | Testimonials | Company | Contact

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);                
    }
}
posted on Wednesday, January 02, 2008 4:37 PM | Filed Under [ ASP.NET Code ]

Comments

Gravatar
# re: Recursively find ASP.NET controls by type with generics
Posted by David Brown
on 7/11/2008 10:32 AM
I tried converting to vb.net, unable to do so. Would you have this in VB.net? If so please forward.

thanks
Gravatar
# re: Recursively find ASP.NET controls by type with generics
Posted by Mendy
on 8/14/2008 5:02 PM
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
Title  
Name
Email (never displayed)
Url
Comments   
Please add 2 and 7 and type the answer here: