Click here to Skip to main content
11,797,944 members (77,708 online)
Click here to Skip to main content

Iterating through menustrip Items

, 3 May 2012 CPOL 29.2K 280 8
Rate this:
Please Sign up or sign in to vote.
This tip explains how you can iterate through all ToolStripMenuItems of a menu strip.


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.


The given code works on a recursive method call.

Using the Code

private void SetToolStripItems(ToolStripItemCollection dropDownItems)
                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.


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


About the Author

Qadeer Ahmed Khan
Software Developer
Pakistan Pakistan
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
shanmugamvasu20-Oct-12 1:07
membershanmugamvasu20-Oct-12 1:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151002.1 | Last Updated 4 May 2012
Article Copyright 2012 by Qadeer Ahmed Khan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid