65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.63/5 (5 votes)

Oct 6, 2011

CPOL
viewsIcon

48602

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:
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:
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.