3

I have been working on a little project and basically it is a parent form that has a child from with Tab Controls inside. When i change tab it adds the relevant options for that tab to the parents menu strip.

What i would like to do is, instead of every time i change tab a new 'Options' appears on the menu strip, so after a few tab changes it has 'Options' 'Options' 'Options' 'Options' on the menu strip, but i would rather remove the options from the previous tab and only have the 1 options displayed.

The code i have so far to remove the options before adding new ones is as follow:

    Dim ParentForm As frmNavigation = frmNavigation

    Dim OptionsMenuStrip As MenuStrip = ParentForm.Controls("MenuStrip1")

    Dim Items As ToolStripItemCollection = OptionsMenuStrip.Items

    For Each Item As ToolStripMenuItem In Items
        If Item.Name = "OptionsMenu" Then
            Item.Dispose()
        End If
    Next

But i am getting the error

'Collection was modified; enumeration operation may not execute.'

Which I understand is basically it saying the collections changing it whilst it's being read, I think?

I just don't know a way around it

Any help to achieve what i want would be greatly appreciated.

I may even be going totally the wrong way about it but i feel so close!

Thanks you :)

dummy
  • 4,256
  • 3
  • 25
  • 36
Pete
  • 469
  • 7
  • 18

1 Answers1

1

Your interpretation of this error is correct. You could put the "to be removed" Items in a seperate List and Remove them afterwards:

    Dim ParentForm As frmNavigation = frmNavigation
    Dim OptionsMenuStrip As MenuStrip = ParentForm.Controls("MenuStrip1")
    Dim Items As ToolStripItemCollection = OptionsMenuStrip.Items
    Dim removeThese As New List(Of ToolStripMenuItem)

    For Each Item As ToolStripMenuItem In Items
        If Item.Name = "OptionsMenu" Then
            removeThese.Add(Item)
        End If
    Next

    For Each item In removeThese
        Items.Remove(item)
        item.Dispose()
    Next

Note that ToolStripMenuItem is removed from the ToolStripItemCollection then disposed.

dummy
  • 4,256
  • 3
  • 25
  • 36
  • I had (from previous search attempts) come across this method but couldn't quite get it working but i will try your code. It does seem like the right way to do it. I will try it now. – Pete Jan 13 '17 at 15:05
  • Thanks so much, Perfect. – Pete Jan 13 '17 at 15:07