Get a list of Components on a Form
A form provides its Controls collection as a way to reference all the controls it hosts. Although it isn't needed as often, it seems odd that there isn't a similar list of non-UI components like Timers, BackgroundWorkers etc. Here is a function that will list all the components on a Form, whether they have been created with the Designer or declared in code:
Code:
Imports System.Reflection
Imports System.ComponentModel
Public Function GetComponents(ByVal frm As Form) As List(Of Component)
Dim components As New List(Of Component)
Dim fieldInfos() As FieldInfo = frm.GetType.GetFields _
(BindingFlags.NonPublic Or BindingFlags.Instance Or _
BindingFlags.DeclaredOnly)
For Each f As FieldInfo In fieldInfos
If f.FieldType.BaseType Is GetType(Component) Then
Dim c As Component = TryCast(f.GetValue(frm), Component)
If c IsNot Nothing Then components.Add(c)
End If
Next
Return components
End Function
Hope it's useful! BB
Re: Get a list of Components on a Form