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

1k views Asked by At

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.

2

There are 2 answers

3
jmcilhinney On BEST ANSWER

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
3
Idle_Mind On

You can recursively search using Controls.Find. This will find the control by name, no matter how deeply nested it is within other controls:

Dim dgvName As String = "dataGridView9001"
Dim dgv As DataGridView = Me.Controls.Find(dgvName, True).FirstOrDefault
If Not IsNothing(dgv) Then
    ' ... do something with "dgv" ...
End If

Note the second parameter of True to the Find() call, telling it to search within children.