This page looks best with JavaScript enabled

VB.NET - Get all controls of specified type from tree

 ·   ·  ☕ 1 min read

Linearise ControlCollection tree into array of Control - generic extension method, no recursion, LINQ or GetNextControl:

 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 
<System.Runtime.CompilerServices.Extension()> 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  newControlSieveList.Add(childControl)  Next  End If  If TypeOf parentControl Is T Then targetControlList.Add(parentControl)  Next  oldControlSieveList = newControlSieveList  End While  Return targetControlList.ToArray End Function 

See attached project for usage/sample (VB.NET 4.0, Visual Studio 2010).


Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)