Search code examples
.netvb.netenumerationmenustriptoolstripmenu

VB .NET Verify checked status of many ToolstripMenuItems


i would like to uncheck all menu items of a main ToolStripMenuItem (called MyMainMenu) in a MenuStrip when i click on another menu entry. The main menu contains some menu items and a separator. I tried the following code:

Private Sub CheckCheckedStatusMenu(ByVal MnuItem As ToolStripMenuItem)
  MnuItem.Checked = True

  For Each Mnu As ToolStripMenuItem In Me.MyMainMenu.DropDownItems
    If Not Mnu Is MnuItem Then
      Mnu.Checked = False
    End If
  Next
End Sub

I call that code from every menu item (except the separator). When i click on a menu item, the program crash saying that he can't make the cast from ToolStripSeparator to ToolStripMenuItem. The same code can be found on the Microsoft .NET documentation site for similar purposes, but it does not specify what can be done in case the same menu item contains different kind of items (separators, textboxes...).

Do you know how can i fix this problem?

Thanks,

Bye


Solution

  • Your code assumes that the DropDownItems only returns items of Type ToolStripmenuItem, but it in fact returns a ToolstripItemCollection

    So you need an extra check to make sure you are only working with the types you are interested in:

    Private Sub CheckCheckedStatusMenu(ByVal MnuItem As ToolStripMenuItem)
        MnuItem.Checked = True
    
        For Each item In Me.MyMainMenu.DropDownItems
            If TypeOf item Is ToolStripMenuItem Then
                Dim mnu = CType(item, ToolStripMenuItem)
                If Not mnu Is MnuItem Then
                    mnu.Checked = False
                End If
            End If
        Next
    End Sub
    

    Probably a better option though is to filter your original collection to only return objects of a particular type:

    Private Sub CheckCheckedStatusMenu(ByVal MnuItem As ToolStripMenuItem)
        MnuItem.Checked = True
    
        For Each mnu In Me.MyMainMenu.DropDownItems.OfType(Of ToolStripMenuItem)
            If Not mnu Is MnuItem Then
                mnu.Checked = False
            End If
        Next
    End Sub
    

    Note that you can further simplify your routine to check only the item that is being passed in:

    Private Sub CheckCheckedStatusMenu(ByVal MnuItem As ToolStripMenuItem)
        For Each mnu In Me.MyMainMenu.DropDownItems.OfType(Of ToolStripMenuItem)
            mnu.Checked = (mnu Is MnuItem)
        Next
    End Sub