0

I have a small project having toolstripmenuitem. I wish to remove toolstripmenuitem during the form_pageLoad()...Is it possible?

My Codes

for each(ToolStripMenuItem dropDownItem in reportstoolStripDropDownButton.DropDownItems) {
if (dropDownItem.Name == MyTable.Rows[M1]["report_menu_name"].ToString()) {
   //MessageBox.Show(dropDownItem.Name);
   reportstoolStripDropDownButton.DropDownItems.Remove(dropDownItem);
}
}

Error Messages:

Invalid OperationException was unhandled - Collection was modified : Enumeration Operation may not execute

Thanks for the helps

dymanoid
  • 14,771
  • 4
  • 36
  • 64
Paramu
  • 613
  • 2
  • 10
  • 23
  • 1
    Possible duplicate of [Collection was modified; enumeration operation may not execute](https://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute) – dymanoid Sep 17 '19 at 19:48
  • Check out [this answer](https://stackoverflow.com/a/207457/3338349) it should have a solution for what you're looking for. If you can use Linq, then utitilize the `RemoveAll` function; if not then you'll need to do a reverse for loop like `for (int i = reportstoolStripDropDownButton.Count() - 1; i >= 0; i--)` – MichaelM Sep 17 '19 at 19:57

1 Answers1

0
string nameToFind = MyTable.Rows[M1]["report_menu_name"].ToString();
List<ToolStripMenuItem> itemsToRemove = new List<ToolStripMenuItem>();

foreach (ToolStripMenuItem dropDownItem in reportstoolStripDropDownButton.DropDownItems)
{
    if (dropDownItem.Name == nameToFind)
    {
        itemsToRemove.Add(dropDownItem);
    }
}

foreach (ToolStripMenuItem dropDownItem in itemsToRemove)
{
    reportstoolStripDropDownButton.DropDownItems.Remove(dropDownItem);
}
Paramu
  • 613
  • 2
  • 10
  • 23