0

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?

rtO
  • 123
  • 1
  • 10
  • Must not be a control that is in a Controls list property. Looks like they abstract it as a special part of the tool strip called a ToolStripItem that is not derived from Control. – Sql Surfer Dec 10 '20 at 23:32
  • 1
    ToolStripItems are special, they do not derive from Control. So you can't find them that way, it isn't obvious why you need it to work. – Hans Passant Dec 10 '20 at 23:33
  • @HansPassant thanks for the info. Long story short, I was trying to disable certain ToolStripItems during a calculation process. Eventually, I'll will go with a solution to disable the ToolStrip. – rtO Dec 10 '20 at 23:44
  • 1
    Related [Access and disable ToolStripItems](https://stackoverflow.com/q/62077316/14171304) – dr.null Dec 11 '20 at 00:00

1 Answers1

1

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
  • @ RicardoEguia thanks for your answer. It solves the problem. I've updated my question because I forgot to mention MenuStrip items. I'll will accept your answer. I just don't know why (and who) disabled the question?! It is a legitimate question and in a matter of minutes two helpful answers have been provided! – rtO Dec 11 '20 at 00:59