C# – Context menu items and subitems

cwinforms

I have a ContextMenuStrip inside a form.

For some reason, I want to change all items of the context menu simultaneously. So I wrote this peace of code:

int a = 0; 

foreach (ToolStripItem co in contextMenuStrip1.Items)  
{     
 co.Text = "Menu" + a.ToString();
  a++;
  }

But although the main items change succesfully, the subitems doesn't change
So how can I have access to those subitems too?

PS: I cannot add an image because I am new to this forum to see what I mean, I hope you get the idea.

Thanks!

Best Answer

You need to cast to ToolStripDropDownItem and check the DropDownItems property. And, of cource, update it recursively.

here is the sample:

public void ChangeMenuItemsNames(ToolStripItemCollection collection)
    {
        foreach (ToolStripMenuItem item in collection)
        {
            item.Name = "New Name";

            if (item is ToolStripDropDownItem)
            {
                ToolStripDropDownItem dropDownItem = (ToolStripDropDownItem)item;

                if (dropDownItem.DropDownItems.Count > 0)
                {
                    this.ChangeMenuItemsNames(dropDownItem.DropDownItems);
                }
            }
        }
    }

How to use:

   this.ChangeMenuItemsNames(this.contextMenuStrip1.Items);