TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

Iterating recursively through menustrip items in C#.NET

There might be many cases and requirements to loop through all menu items in a Menu Strip Control.The sample method here help you to achieve the same.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.

There might be many cases and requirements to loop through all menu items in a MenuStrip Control.The following sample method help you to achieve the same.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.

The Innovators: How a Group of Inventors, Hackers, Geniuses and Geeks Created the Digital Revolution

public class MenuStripItems
    {
        List<ToolStripMenuItem> toolSripItems = null;

        //Extract all menu strip items
        private List<ToolStripMenuItem> GetMenuStripItems(MenuStrip menuStrip)
        {
            toolSripItems = new List<ToolStripMenuItem>();
            foreach (ToolStripMenuItem toolSripItem in menuStrip.Items)
            {
                GetSubMenuStripItems(toolSripItem);
            }
            return toolSripItems;
        }

      
        //This method is called recursively inside to loop through all menu items
        private void GetSubMenuStripItems(ToolStripMenuItem menuItem)
        {
            toolSripItems.Add(menuItem);

            // if sub menu contain child dropdown items
            if (menuItem.HasDropDownItems)          
            {
                foreach (ToolStripItem toolSripItem in menuItem.DropDownItems)
                {
                    if (toolSripItem is ToolStripMenuItem)
                    {
                        //call recursively
                        GetSubMenuStripItems((ToolStripMenuItem)toolSripItem);
                    }
                }
            }
         
        }

    }

Submit your site to best web directory! Find sites like this in the Software Engineering Directory

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading