Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to iterate recursive through all menu items in a menuStrip Control

4.63/5 (5 votes)
7 Oct 2011CPOL 48.5K  
How to iterate recursively through all menu items in a menuStrip Control
For a multilanguage project last time i faced the problem how to translate the menu entries of a menuStrip Control and enable/disable the controls for security settings.

So i created a small helper class to get a list of all entries and i like to share with u the solution.

Basically it's a simple recursive iteration;
So here we go:

XML
namespace Test_MenuItemIteration
{
    using System.Collections.Generic;
    using System.Windows.Forms;

    public static class GetAllMenuStripItems
    {
        #region Methods

        /// <summary>
        /// Gets a list of all ToolStripMenuItems
        /// </summary>
        /// <param name="menuStrip">The menu strip control</param>
        /// <returns>List of all ToolStripMenuItems</returns>
        public static List<ToolStripMenuItem> GetItems(MenuStrip menuStrip)
        {
            List<ToolStripMenuItem> myItems = new List<ToolStripMenuItem>();
            foreach (ToolStripMenuItem i in menuStrip.Items)
            {
                GetMenuItems(i, myItems);
            }
            return myItems;
        }

        /// <summary>
        /// Gets the menu items.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="items">The items.</param>
        private static void GetMenuItems(ToolStripMenuItem item, List<ToolStripMenuItem> items)
        {
            items.Add(item);
            foreach (ToolStripItem i in item.DropDownItems)
            {
                if (i is ToolStripMenuItem)
                {
                    GetMenuItems((ToolStripMenuItem)i, items);
                }
            }
        }

        #endregion Methods
    }
}



[GetItems] iterates through the TopLevel menus and call [GetMenuItems]
GetMenuItems checks whether DropDwonItems exists or not.
If yes, it will call itself to find all levels of menu entries.

How to use the code in your App:

XML
List<ToolStripMenuItem> myItems = GetAllMenuStripItems.GetItems(this.menuStrip1);
foreach (var item in myItems)
{
    MessageBox.Show(item.Text);
}


Hope the snippet is usefull and easy to understand.

License

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