Recursively find ASP.NET controls by type with generics
January 2. 2008 5 Comments
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
Thanks, that helped me a lot! :)
ArsiYour 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.
Eric Chaupublic 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);
}
}
}
I tried converting to vb.net, unable to do so. Would you have this in VB.net? If so please forward.
David Brownthanks
Public Function FindControls(Of T) where (Of T) : Control(ByVal parent As Control) As List(Of T)
MendyDim 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
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.
Richard CollettePublic 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