65.9K
CodeProject is changing. Read more.
Home

Iterating through menustrip Items

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (6 votes)

May 2, 2012

CPOL
viewsIcon

55791

downloadIcon

583

This tip explains how you can iterate through all ToolStripMenuItems of a menu strip.

Introduction

It is quite difficult to set the properties of toolstrip menu items like if you want to disable certain items or make them invisible. It is simple to set them individually, but if you want to iterate through all the items, it's quite difficult. This tip explains how you can iterate through all ToolStripMenuItems of a menu strip.

Background

The given code works on a recursive method call.

Using the Code

private void SetToolStripItems(ToolStripItemCollection dropDownItems)
        {
            try
            {
                foreach (object obj in dropDownItems)
                //for each object.
                {
                    ToolStripMenuItem subMenu = obj as ToolStripMenuItem;
                    //Try cast to ToolStripMenuItem as it could be toolstrip separator as well.

                    if (subMenu != null)
                    //if we get the desired object type.
                    {
                        if (subMenu.HasDropDownItems) // if subMenu has children
                        {
                            SetToolStripItems(subMenu.DropDownItems); // Call recursive Method.
                        }
                        else // Do the desired operations here.
                        {
                            if (subMenu.Tag != null)
                            {
                                subMenu.Visible = UserRights.Where(x => 
                                x.FormID == Convert.ToInt32(subMenu.Tag)).First().CanAccess;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SetToolStripItems",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        } 

Points of Interest

Recursive methods are quite useful when you don't know the depth of the loops.