I had learnt by reading your great answers here, that it is not good practice deleting items from within a foreach loop, as it is (and I quote) “Sawing off the branch you’re sitting on”.
My code currently removes the text from the dropdownlist, but the actual item remains (just without text displayed).
In other words, it isn’t deleting, and probably can’t because you can’t delete from within a foreach loop.
After hours of trying I am unable to get my head around a way of doing it.
//For each checked box, run the delete code
for (int i = 0; i < this.organizeFav.CheckedItems.Count; i++)
{
//this is the foreach loop
foreach (ToolStripItem mItem in favoritesToolStripMenuItem.DropDownItems)
{
//This rules out seperators
if (mItem is ToolStripMenuItem)
{
ToolStripMenuItem menuItem = mItem as ToolStripMenuItem;
//This matches the dropdownitems text to the CheckedItems String
if (((ToolStripMenuItem)mItem).Text.ToString() == organizeFav.CheckedItems[i].ToString())
{
//And deletes the item
menuItem.DropDownItems.Remove(mItem);
}
}
}
}
But it isn’t deleting because it is within a foreach loop!
I would greatly appreciate your help, and be truly amazed if anyone can get their head around this code 🙂
Kind Regards
You don’t need a
foreachloop – just use a regular loop but go in reverse, start at the end and go to the beginning.this was @Kurresmack’s code rearranged, i just coded it directly here in the page so excuse any small syntax error or anything obvious i overlooked (disclaimer: it is a sample!!)
You can still treat
favoritesToolStripMenuItem.DropDownItemsas a collection like you were, but you don’t have to enumerate over it using aforeach. This cuts down on a few lines of code, and it works because you are iterating it in reverse order, you will not get an index out of bounds exception.