rtO
rtO

Reputation: 123

vb.net Find all child controls in a winform

I have a win forms application where one of the forms has many controls in different containers (FlowLayoutPanels) and ToolStrip controls within. I need to find all child controls in the form (and in the containers). The following recursive function works to a certain degree, but it fails to find child elements in ToolStrip, MenuStrip and similar control items (buttons, labels, comboboxes, etc.).

Public Sub FindChildren(ByVal parentCtrl As Control, ByRef children As List(Of Control))
  If parentCtrl.HasChildren Then
    For Each ctrl As Control In parentCtrl.Controls
      children.Add(ctrl)
      Call FindChildren(ctrl, children)
    Next ctrl
  End If
End Sub

Any suggestions how to enumerate ToolStrip items?

Upvotes: 0

Views: 1327

Answers (1)

Ricardo Eguia
Ricardo Eguia

Reputation: 101

YOu can change the list to list of objects and use the following code:

Public Sub FindChildren(ByVal parentCtrl As Control, ByRef children As List(Of Object))
    If parentCtrl.HasChildren Then
        For Each ctrl As Control In parentCtrl.Controls
            If TypeOf ctrl Is ToolStrip Then
                Dim toll As ToolStrip
                toll = ctrl
                For Each item In toll.Items

                    children.Add(item)
                Next item

            End If
            children.Add(ctrl)
            Call FindChildren(ctrl, children)
        Next ctrl
    End If

End Sub

Upvotes: 1

Related Questions