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 article 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
foreach (ToolStripMenuItem mainMenu in ts.Items)
{
if (mainMenu.Visible)
{
SetToolStripItems(mainMenu.DropDownItems);
}
}
private void SetToolStripItems(ToolStripItemCollection dropDownItems)
{
try
{
foreach (object obj in dropDownItems)
{
if (obj.GetType().Equals(typeof(ToolStripMenuItem)))
{
ToolStripMenuItem subMenu = (ToolStripMenuItem)obj;
if (subMenu.HasDropDownItems) {
SetToolStripItems(subMenu.DropDownItems); }
else {
if (subMenu.Tag != null)
{
subMenu.Visible =
AccountsGlobals.FormRights(Convert.ToInt32(subMenu.Tag)).CanAccess;
subMenu.Enabled =
AccountsGlobals.FormRights(Convert.ToInt32(subMenu.Tag)).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.