Results 1 to 2 of 2

Thread: Get a list of Components on a Form

  1. #1
    Frenzied Member boops boops's Avatar
    Join Date
    Nov 08
    Location
    Holland/France
    Posts
    1,982

    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
    Last edited by boops boops; Jul 11th, 2010 at 05:13 PM.

  2. #2
    Pro Grammar chris128's Avatar
    Join Date
    Jun 07
    Location
    England
    Posts
    7,534

    Re: Get a list of Components on a Form

    Pretty neat
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

    Blog: cjwdev.wordpress.com
    Web: www.cjwdev.co.uk


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •