Wednesday, September 24, 2008

How to get the index (GetIndex) from a ToolStripMenuItem

When we converted our application to VB.NET.  The upgrade wizard created this VB6.MenuItemArray, then using it it set the indices for all the menu items that were in it.  So when a user clicked on one of its menu items.  The .Click event was called and inside this a function called GetIndex was called and in our application we used this index to figure out what menu item was clicked.  Below is a short example of the code in our .Click event.

  Public Sub MenuBrushSize_Click(ByVal eventSender As System.Object, ByVal e As System.EventArgs) Handles MenuBrushSize.Click
    Dim Index As Short = MenuBrushSize.GetIndex(eventSender)
    Select Case Index
      Case 0
        'do something
      Case 1
        'do something
      Case 2
        'do something
      Case Else
        'do something
    End Select
  End Sub

When I moved over to 2005 and decided to use the ContextMenuStrip and subsequently the ToolStripMenuItem, I decided not to use the VB6.MenuItemArray.  But then I didn't want to have separate handler routines for each and every one of my menu items.  I wanted to have it all in one Subroutine.  But there isn't a GetIndex function for the ToolStripMenuItem.  So I had to create one, below is how I was able to do it:

  Public Function GetMenuItemIndex(ByVal sender As System.Object) As Short
    Dim oMenuItem As New System.Windows.Forms.ToolStripMenuItem
    oMenuItem = CType(sender, System.Windows.Forms.ToolStripMenuItem)
    If TypeOf oMenuItem.Owner Is ContextMenuStrip Then
      Dim parentMenu As ContextMenuStrip = oMenuItem.Owner
      For index As Integer = 0 To parentMenu.Items.Count - 1
        If oMenuItem.Name = parentMenu.Items(index).Name Then
          Return index
        End If
      Next
    ElseIf TypeOf oMenuItem.Owner Is ToolStrip Then
      Dim parentMenu As ToolStrip = oMenuItem.Owner
      For index As Integer = 0 To parentMenu.Items.Count - 1
        If oMenuItem.Name = parentMenu.Items(index).Name Then
          Return index
        End If
      Next
    End If
  End Function

This function basically checks the parent of the current menu, and gets the index of that menu item.  Basically I assume the menu item is part of some collection and I want to find out the index in the collection.

Below is how I use it.  Its pretty much the same, execept now my handles must specify all the menu items we are handling.

  Public Sub MenuBrushSize_Click(ByVal eventSender As System.Object, ByVal e As System.EventArgs) Handles _
    MenuBrushSize_0.Click, MenuBrushSize_1.Click, MenuBrushSize_2.Click, MenuBrushSize_3.Click

    Dim Index As Short = GetMenuItemIndex(eventSender)
    Select Case Index
      Case 0
        'do something
      Case 1
        'do something
      Case 2
        'do something
      Case Else
        'do something
    End Select
  End Sub


No comments: