C#

Iterating recursively through menustrip items in C#.NET

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);
                     }
                 }
              }
         }
}
Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

2 years ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

2 years ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

2 years ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

2 years ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

2 years ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

2 years ago