Search code examples
vb.netcontrolsctype

Find all controls on a form, even those within Tab Controls - VB.net


I have a set of DataGridViews that are created at run time and I need to reference these to update them when changes are made. I know that I can use

Dim dgvUpdate As DataGridView
dgvUpdate = CType(Me.Controls(strGridName), DataGridView)

to get hold of the datagrid I need and them re-run the SQL and re-do the DataGridView.DataSource.

However these DataGridViews are located within TabPages within any number of different TabControls and so do not appear in Me.Controls

Is there a way of being able, in code, to reference all controls within the current form, regardless of tabs, panels etc. that I can use in the Ctype method to grab the correct datagridview.


Solution

  • Here's a method you can use to get every control on a form in Tab order:

    Public Iterator Function GetControls() As IEnumerable(Of Control)
        Dim ctrl = GetNextControl(Me, True)
    
        Do Until ctrl Is Nothing
            Yield ctrl
    
            ctrl = GetNextControl(ctrl, True)
        Loop
    End Function
    

    If you wanted to use that to get every DataGridView:

    For Each grid In GetControls().OfType(Of DataGridView)()
        'Use grid here.
    Next
    

    If you wanted to be more direct, this will get every DataGridView on any TabPage of a specific TabControl:

    For Each grid In TabControl1.TabPages.
                                 Cast(Of TabPage)().
                                 SelectMany(Function(tp) tp.Controls.OfType(Of DataGridView)())
        'Use grid here.
    Next