I want to get all the SubItems
of my MenuStrip
, So I can change them all at once.
I'am trying things like the following, but they aren't working:
foreach (ToolStripMenuItem toolItem in menuStrip1.DropDownItems)
{
//Do something with toolItem here
}
Can someone help me out coding a good foreach loop
for getting all the SubMenuItems(DropDownItems)
from the MenuStrip
?
EDIT now trying to work with the following Recursive method
:
private void SetToolStripItems(ToolStripItemCollection dropDownItems)
{
try
{
foreach (object obj in dropDownItems)
{
if (obj.GetType().Equals(typeof(ToolStripMenuItem)))
{
ToolStripMenuItem subMenu = (ToolStripMenuItem)obj;
if (subMenu.HasDropDownItems)
{
SetToolStripItems(subMenu.DropDownItems);
}
else
{
}
}
}
}
catch
{
}
}
You've actually got the type wrong,
DropDownItems
contains a collection ofToolStripItem
not a collection ofToolStripMenuItem
.Try this instead:
Or in your function:
Below is an extension class to get all
ToolStripMenuItem
s. The advantage here is that all code is in one recursive method. One can easily convert this to a generic method if other menu item types are needed.Try this:
It seems you cannot do it with direct 'foreach' approach. I think I figured it out.
Adding menu items manually to a list is a bit barbarian, but using 'foreach' or 'for' or other cycles gave me the same error. something about enumeration. It seems like they cannot count all the menu items by themselves :P On the other hand, if you have items like seperators and other stuff, that is not quite like a simple menu item, putting them all in one list and trying to rename would raise another problem.
This is for changing the text displayed on menu items, but you can do absolutely anything you want with them using this method.
For .net 4.5 and above I've used this to get dropdownitems for a specific toolstripmenuitem.
Here is a very simple solution