Simos Sigma
Simos Sigma

Reputation: 978

ToolStripMenuSeparator prevents Disable/Enable programmatically of ToolStripMenuItems

I am using this part of code below to disable some ToolStripMenuItems whose tag is M2 for example. The problem is that code works, untill it "meets" the first ToolStripMenuSeparator. Even if ToolStripMenuItems under ToolStripMenuSeparator have M2 as tag, remain enabled. If I manually remove the ToolStripMenuSeparator everything is okay!!! There is any difference in case we have a separator between menu items?

Dim MenuItem As ToolStripMenuItem
    For Each MenuItem In MainForm_MenuStrip.Items
        If (MenuItem.GetType() Is GetType(ToolStripMenuItem)) Then
            Dim MenuSubItem As ToolStripMenuItem
            For Each MenuSubItem In MenuItem.DropDownItems
                If (MenuSubItem.GetType() Is GetType(ToolStripMenuItem)) And MenuSubItem.Tag = "M2" Then
                    MenuSubItem.Enabled = False
                End If
            Next
        End If
    Next

Upvotes: 0

Views: 142

Answers (1)

MatSnow
MatSnow

Reputation: 7517

The main problem is that ToolStripSeparator can not be casted to ToolStripMenuItem. So the following line will throw an InvalidCastException as soon as the loop reaches the ToolStripSeparator:

For Each MenuSubItem In MenuItem.DropDownItems

If you cast to ToolStripItem instead it will work fine. Furthermore you should define MenuItem as Object instead, otherwise your code will fail as soon as there's a ToolStripTextbox or ToolStripCombobox in the menu. Also the GetType-parts can be replaced with TypeOf.

For Each MenuItem As Object In Mainform_MenuStrip.Items
    If TypeOf MenuItem Is ToolStripMenuItem Then
        For Each MenuSubItem As ToolStripItem In MenuItem.DropDownItems
            If TypeOf MenuSubItem Is ToolStripMenuItem AndAlso MenuSubItem.Tag = "M2" Then
                MenuSubItem.Enabled = False
            End If
        Next
    End If
Next

This example uses late-binding.
Following will also work with Option Strict On:

For Each MenuItem As ToolStripItem In Mainform_MenuStrip.Items
    If TypeOf MenuItem Is ToolStripMenuItem Then
        For Each MenuSubItem As ToolStripItem In DirectCast(MenuItem, ToolStripMenuItem).DropDownItems
            If TypeOf MenuSubItem Is ToolStripMenuItem AndAlso CStr(MenuSubItem.Tag) = "M2" Then
                MenuSubItem.Enabled = False
            End If
        Next
    End If
Next

Upvotes: 1

Related Questions