Search code examples
vb.netcontrolsmenustrip

Dynamic Menustrip access vb.net


I'm adding MenuStrips dynamically based on number of rs232 ports available. The thing is i want to access the controls text in order to use them in the connection.

Private Sub FormConnection_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    myPort = IO.Ports.SerialPort.GetPortNames()

    Dim Ports As Array = CType(myPort, Object())
    If Ports.Length = 0 Then
        MessageBox.Show("No connections available.")
    Else

        Dim PortsLength As Integer = Ports.Length
        For Length As Integer = 0 To PortsLength - 1

            Dim Item As New ToolStripMenuItem(Ports(Length).ToString, Nothing, _
            New EventHandler(AddressOf MenuCOMclick))
            Item.CheckOnClick = True
            Item.Name = "COMDYN" + Length.ToString
            PortsToolStripMenuItem.DropDownItems.Add(Item)
        Next
End If

Now i want to add a Event MenuCOMclick where one of the menus is clicked, all the others are unchecked.

I tried to create an array of controls but the menustrips don't work like that.. How can i do that then ?

Private Sub MenuCOMclick(ByVal sender As Object, ByVal e As EventArgs)
   ???
   ???
   ???
End Sub

Thank you


Solution

  • thats the way to access ToolStripMenuItems in your MenuStrip, note that if you want to access the sender (the control that was raised the event) you need to cast the sender to the control type.

    also you can itterate all ToolStripMenuItems. read my comments, hope it helps.

    Private Sub MenuCOMclick(ByVal sender As Object, ByVal e As EventArgs)
        ' thats how you can check the name of the sender
        MsgBox(CType(sender, ToolStripMenuItem).Name)
        ' thats how you can itterate all ToolStripMenuItem 
        For Each itm As ToolStripMenuItem In MenuStrip1.Items
            For Each Childitm As ToolStripMenuItem In itm.DropDownItems
                MsgBox(Childitm.Name) ' show name of the item
                ' example to access all items properties accept the sender
                If Childitm.Name <> CType(sender, ToolStripMenuItem).Name Then
                    itm.ForeColor = Color.Beige
                End If
            Next
        Next
    End Sub