Reputation: 1201
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!
Upvotes: 0
Views: 6373
Reputation: 5762
void ChangeName(ToolStripItemCollection collection, ref int a)
{
foreach (ToolStripItem co in collection)
{
co.Text = "Menu" + a.ToString();
a++;
if (co is ToolStripDropDownItem)
{
ToolStripDropDownItem ts = co as ToolStripDropDownItem;
if (ts.DropDownItems != null) ChangeName(ts.DropDownItems, ref a);
}
}
}
Upvotes: 0
Reputation: 30175
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);
Upvotes: 4
Reputation: 1919
Since as per MSDN, ToolStripButton,ToolStripLabel,ToolStripSeparator,ToolStripControlHost,ToolStripDropDownItem,ToolStripStatusLabel do inherit from ToolStripItem, you can try casting with as operator and then setting its text property as well.
Hope this is what your asking for.
Upvotes: 0