Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a small project having toolstripmenuitem. I wish to remove toolstripmenuitem during the form_pageLoad()...Is it possible?

My Codes
C#
<pre>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

What I have tried:

Tried to remove toolstripmenuitem programmatically
Posted
Updated 17-Sep-19 23:49pm

You'll need to remove the item from outside of the foreach loop. For example:
C#
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);
}
 
Share this answer
 
Comments
BillWoodruff 18-Sep-19 5:51am    
You could use a Cast here to avoid two loops. I would not use iteration (see my code below).
A different approach: I have deliberately used multiple checks for valid names; in production code, I'd use try/catch.
private void RemoveDDownMenuItem(MenuStrip mnuStrip, string menuItemName, string ddownMenuItemName)
{
    if (! mnuStrip.Items.ContainsKey(menuItemName))
    {
        // throw error ?
        return;
    }

    ToolStripItem menu = mnuStrip.Items[menuItemName];

    if(! (menu is ToolStripMenuItem))
    {
        // throw error ?
        return;
    }

    ToolStripMenuItem tsmenu = (ToolStripMenuItem) menu;

    if (! tsmenu.HasDropDown)
    {
        // throw error ?
        return;
    }

    if (! tsmenu.DropDownItems.ContainsKey(ddownMenuItemName))
    {
        // throw error ?
        return;
    }
    
    tsmenu.DropDownItems.Remove(tsmenu.DropDownItems[ddownMenuItemName]);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900