views:

748

answers:

1

I have a Windows Forms application, written in VB.NET framework 2.0.

I have a grid that has an associated context menu with the following structure :

MenuItem1
MenuItem2 -->
             SubMenuItem1
             SubMenuItem2 -->
                             SubSubMenuItem1
MenuItem3
...

I wish to display the context menu when a particular key is pressed within the grid, and have the 'SubMenuItem1' selected programmatically.

I can display the context menu by invoking the Show() method on the context menu item from the grid's KeyUp event in the following manner:

contextMenu.Show(MainForm.GetSingleton(), Cursor.Position)

I can't however figure out how to programmatically select an item in the sub menu or sub sub menu.

Can anyone help?

+1  A: 

This may be the biggest most ugly peice of code if someone shows up in five minutes with something like: ToolStripMenuItem8.selectAllParents(). But as far as I could see there wasn't any function like that.

So here is what I could come up with:

    Private Sub openTSMitem(ByVal menu As ContextMenuStrip, ByVal selectitem As ToolStripMenuItem)

    'The menu needs to be open befor we call ShowDropDown
    menu.Show()

    'The list will first contain the parents in the order of bottom to top
    'then we will reverse it so we can open the submenus from top to bottom
    'otherwise it will not open them all
    Dim parentsRevOrder As ArrayList = New ArrayList()

    'Add the parents to the list
    Dim parentItem As ToolStripMenuItem = selectitem.OwnerItem
    While Not parentItem Is Nothing
        parentsRevOrder.Add(parentItem)
        parentItem = parentItem.OwnerItem
    End While
    'reverse the list. now its in the order top to bottom
    'and the submenus will open correctly
    parentsRevOrder.Reverse()

    'now loop through and open the submenus
    For Each tsiParent As ToolStripMenuItem In parentsRevOrder
        tsiParent.ShowDropDown()
    Next

    'and finally select the menuItem we want
    selectitem.Select()

End Sub

And then call the sub:

openTSMitem(ContextMenuStrip1, ToolStripMenuItem8)

Hope it helps.

Edit: I just saw that the comments and code showed up a bit mixed in the answer, just paste it in to Visual Studio though , and it should look just fine

Charlie boy
Thanks. I'll have a look at this and get back to you, it may however take a day or two to sort through.
Jayden
This works great. I hadn't been using the ContextMenuStrip, but rather the ContextMenu control (this project was upgraded from a .NET 1.1 project). I've now converted menus to these types of controls to take advantage as the old ContextMenuItems don't have the ShowDropDown() method.Thanks!
Jayden