Results 1 to 2 of 2

Thread: Get a list of Components on a Form

Threaded View

  1. #1

    Thread Starter
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    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.

Posting Permissions

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



Click Here to Expand Forum to Full Width