Reputation: 635
In my Winforms application I have a ToolStripMenuItem with nested sub-items, the structure of which is shown below.
File
.+...Add As....+.....File
............................Folder
............................Root Folder
Under 'Add As' I want to be able to programmatically enable and disable 'File', 'Folder', and 'Root Folder' as required. How can I access these nested items in code?
I have tried ToolStripMenuItem.DropDownItems[0].Enabled = true\false; but this affects 'Add As' and everything below it in the menu hiearachy.
If I use an index greater than zero in the code above I get an 'index out of range' error. How do I go about achieving this functionality?
Upvotes: 1
Views: 9152
Reputation: 81610
As Hans' hinted in his comment, you are referencing the wrong DropDownItems collection.
To do this using indexes will get ugly quickly.
It's simpler to just reference the parent menu and loop through "its" menu collection:
private void toggleMenu_Click(object sender, EventArgs e) {
foreach (ToolStripMenuItem toolItem in addAsToolStripMenuItem.DropDownItems) {
toolItem.Enabled = !toolItem.Enabled;
}
}
Here is the ugly method, which would be difficult to maintain if you decided later to rearrange your menu structure:
foreach (ToolStripMenuItem toolItem in ((ToolStripMenuItem)((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems[0]).DropDownItems) {
toolItem.Enabled = !toolItem.Enabled;
}
Upvotes: 3
Reputation: 1294
Simply reference the sub-items by their own names eg:
FileToolStripMenuItem.Enabled = false;
FolderToolStripMenuItem.Enabled = false;
RootFolderToolStripMenuItem.Enabled = false;
Unless I'm missing something, this seems like the simplest answer.
Upvotes: 7