Simonetos Simonetos - 2 years ago 246 Question

VB.NET - How to delete multiple items from a ToolStrip?

I have make a ToolStrip works like windows task bar. When user opens a new form, a label with form's icon appears on ToolStrip as new label item. I also have a button that closes all forms at once. But I want to remove every relevant label too, so I added this into the click event...

For Each mdichildlabel As ToolStripLabel In Me.BottomToolStrip.Items
If mdichildlabel.Name = "NewLabel" Then
End If

But I get this error:
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll

Answer Source

Doesn't work doesn't tell us what you are seeing that is not working.

Generally, you can't modify a collection while for-eaching it because of the changing index positions. Try iterating over it backwards:

For i As Integer = Me.BottomToolStrip.Items.Count - 1 to 0 Step -1
  If Me.BottomToolStrip.Items(i).Name = "NewLabel" Then
  End If
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download