There's a toolstripmenuitem in my Windows form Application. I need to access every sub menu items and check whether there is a specific menu item name is available and if that item found, I want to disable it. Eg:
Report
|__Stock
| |__Stock Balance
| |__Stock Reorder
|__Sales
|__Summary
My code is like this. According to my code, I can access sub menu(Stock) and disable it. But I'm unable to access child items(Stock Balance) inside sub menu.
String specificMenuItemName = "Stock Balance";
foreach (ToolStripMenuItem menuItem in MainMenuStrip.Items)
{
if (menuItem != null)
{
if (menuItem.HasDropDownItems)
{
foreach (ToolStripItem subMenuItem in menuItem.DropDownItems)
{
if (subMenuItem is ToolStripSeparator)
{ }
else
{
if (specificMenuItemName == subMenuItem.Text)
{
subMenuItem.Enabled = false;
}
}
}
}
}
}
How do I access to Stock Balance and disable it?
What about a recursive function that walks down every item that has drop-down items until it finds the one with the specified name? something like this (quick-and-dirty, skipped checking for separators and stuff like that...):
private static void DisableItem(ToolStripDropDownItem menu, bool enable, string text)
{
if (!menu.HasDropDownItems)
if (Equals(menu.Text, text))
menu.Enabled = enable;
else
return;
foreach(var subItem in menu.DropDownItems)
{
var item = subItem as ToolStripDropDownItem;
if (item == null) continue;
if (item.HasDropDownItems)
DisableItem(item, enable, text);
if (Equals(item.Text, text))
item.Enabled = enable;
}
}