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
{
}
}
Try this:
List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem toolItem in menuStrip.Items)
{
allItems.Add(toolItem);
//add sub items
allItems.AddRange(GetItems(toolItem));
}
private IEnumerable<ToolStripMenuItem> GetItems(ToolStripMenuItem item)
{
foreach (ToolStripMenuItem dropDownItem in item.DropDownItems)
{
if (dropDownItem.HasDropDownItems)
{
foreach (ToolStripMenuItem subItem in GetItems(dropDownItem))
yield return subItem;
}
yield return dropDownItem;
}
}