1
votes

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?

2
Please don't prefix your titles with "C# - " and such. That's what the titles are for. - John Saunders
You are not going deep enough. The simple way is to just use the named variables that the Winforms designer generates for you. - Hans Passant

2 Answers

3
votes

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;
  }
7
votes

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.