Dynamic ContextMenuStrip SubItems

sollniss

Member
Joined
Aug 5, 2008
Messages
12
Programming Experience
3-5
Hey guys, ive got a problem with the ContextMenuStrip.

My setting:
I've gote a few Buttons und for each button the same contextmenu. It's opening on left, not on right click. The contextmenu items are eg. A, B and C.
Well, contextmenu item A as some subitems, i call them a, b and c.

If i click on button 1 now, the contextmenu opens and i can choose an item, the clicked item will be selected and the button.text changed to the item.text.
If i click on button 2 and choose another item the same. But, if i click on button 1 again the item with the button1.text is checked, und if i click on button 2 the button2.text is checked. I've done that with button.tag.

My problem:
How can i do the same thing with the subitems?

Here is an excample code for my setting:
VB.NET:
Public Class Form1
  Private Sub Form1_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
 
    Button1.Text = "A"
    Button2.Text = "B"
 
    With ContextMenuStrip1
      .Items.Add(New ToolStripMenuItem("A"))
      .Items.Add(New ToolStripMenuItem("B"))
    End With
  End Sub
 
  Private Sub Button_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click
 
    ' Kontextmenü aufrufen
    Dim oButton As Button = CType(sender, Button)
    With ContextMenuStrip1
      .Tag = oButton
      For Each oItem As ToolStripMenuItem In .Items
        oItem.Checked = (oItem.Text.Equals(oButton.Text))
      Next
      .Show(oButton, 0, oButton.Height)
    End With
  End Sub
 
  Private Sub ContextMenuStrip1_ItemClicked(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) _
    Handles ContextMenuStrip1.ItemClicked
 
    Dim oButton As Button = CType(ContextMenuStrip1.Tag, Button)
    oButton.Text = e.ClickedItem.Text
  End Sub
End Class

btw, if i click on an item, the buttontext should be changed and the contextmenu closed. Defaultly the subitem-list is opened when i click on it.

PS. sorry for my bad english I'm not a native speaker. ^^
 
Back
Top