Tech Blog‎ > ‎

VB.NET - Get All Controls Of Specified Type From ControlCollection Tree

posted May 8, 2012, 7:58 AM by Victor Zakharov   [ updated May 8, 2012, 8:00 AM ]
Linearise ControlCollection tree into array of Control - generic extension method, no recursion, LINQ or GetNextControl:

Friend Function GetAllControlsOfType(Of T As Control)(ByVal controls As Control.ControlCollection) As T()
  Dim controlsArray(controls.Count - 1) As Control
  controls.CopyTo(controlsArray, 0)
  Dim oldControlSieveList As New List(Of Control)(controlsArray)
  Dim newControlSieveList As List(Of Control)
  Dim targetControlList As New List(Of T)
  While oldControlSieveList.Count > 0
    newControlSieveList = New List(Of Control)
    For Each parentControl As Control In oldControlSieveList
      If parentControl.HasChildren Then
        For Each childControl As Control In parentControl.Controls
      End If
      If TypeOf parentControl Is T Then targetControlList.Add(parentControl)
    oldControlSieveList = newControlSieveList
  End While
  Return targetControlList.ToArray
End Function

See attached project for usage/sample (VB.NET 4.0, Visual Studio 2010).
Victor Zakharov,
May 8, 2012, 7:58 AM