Let's say I have MenuStrip
with ToolStripMenuItem
named fileToolStripMenuItem
(with text File
) which have subitems New
and Open
. Furthermore, Open
has From file
and Recent
. To access all File
's ToolStripMenuItems
(it's children), you need recursive method, which goes through all levels (to access children, grandchildren...)
private IEnumerable<ToolStripMenuItem> GetChildToolStripItems(ToolStripMenuItem parent)
{
if (parent.HasDropDownItems)
{
foreach (ToolStripMenuItem child in parent.DropDownItems)
{
yield return child;
foreach (var nextLevel in GetChildToolStripItems(child))
{
yield return nextLevel;
}
}
}
}
This method takes first level menu item and returns IEnumerable<ToolStripMenuItem>
sou you can then iterate through it (to get name, change some property etc).
Use it like this:
var list = GetChildToolStripItems(fileToolStripMenuItem);
In my example, that will return you the collection of subitems, like this: New, Open, From File, Recent
.
You can easily go through collection and get item's text (to display in MessageBox
, like this:
MessageBox.Show(string.Join(", ", list.Select(x=>x.Text).ToArray()))
or, if you prefer, like this:
foreach (ToolStripMenuItem menuItem in list)
{
MessageBox.Show(string.Format("item named: {0}, with text: {1}", menuItem.Name, menuItem.Text));
}
EDIT: after I saw comment that OP's idea is to get all items from MenuStrip
, here's an example for that.
I wrote additional method that takes MenuStrip
as parameter, iterates throught all ToolStripMenuItems
and for each item calls GetChildToolStripItems
method. Returns list of all top level items and all children and grand children...
private List<ToolStripMenuItem> GetAllMenuStripItems(MenuStrip menu)
{
List<ToolStripMenuItem> collection = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem item in menu.Items)
{
collection.Add(item);
collection.AddRange(GetChildToolStripItems(item));
}
return collection;
}
usage:
var allItems = GetAllMenuStripItems(menuStrip1)
Hope this helps.