Iterating Through Menustrip Items: There might be many cases and requirements to loop through all menu items in a menustrip Control. So, How to iterate recursively through all menu items in a menustrip control?
The following is a sample method to help you in iterating through menustrip items.You can use these methods in the same class or can be made as separate static utility methods as you like.I just made it as private methods inside a class.
C# – Iterate Recursive Through all Menu Items in a MenuStrip Control
public class MenuStripItems { <ToolStripMenuItem> toolSripItems = null; //Extract all menu strip items private List<ToolStripMenuItem> GetAllMenuStripItems(MenuStrip mnuStrip) { toolSripItems = new List<ToolStripMenuItem>(); foreach (ToolStripMenuItem toolSripItem in mnuStrip.Items) { GetAllSubMenuStripItems(toolSripItem); } return toolSripItems; } //This method is called recursively inside to loop through all menu items private void GetAllSubMenuStripItems(ToolStripMenuItem mnuItem) { toolSripItems.Add(mnuItem); // if sub menu contain child dropdown items if (mnuItem.HasDropDownItems) { foreach (ToolStripItem toolSripItem in mnuItem.DropDownItems) { if (toolSripItem is ToolStripMenuItem) { //call the method recursively to extract further. GetAllSubMenuStripItems((ToolStripMenuItem)toolSripItem); } } } } }
Leave a Reply