C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Every item can be accessed using a foreach-loop. In this way we can disable all ToolStripItems. This control is used in a Menu control in Windows Forms.
Example. I had a requirement to disable all the ToolStripItem controls when the program went into "password protected" mode. This code disables all the menu items in two menus, the File and Tools menus.
Here are two methods that set menus to enabled or disabled. When Enabled is changed to false, the menu will turn gray. The methods must be called manually: we can call them from the code in an event handler.
Example code that disables menu: C# void EnableFileToolsMenu(bool state) { foreach (ToolStripItem item in fileToolStripMenuItem.DropDownItems) { item.Enabled = state; } foreach (ToolStripItem item in toolsToolStripMenuItem.DropDownItems) { item.Enabled = state; } } void EnableEditMenu(bool state) { foreach (ToolStripItem item in editToolStripMenuItem1.DropDownItems) { item.Enabled = state; } }
Both methods receive a bool called state. Our callers will specify this value. True means to enable all the menu items, and false means to set Enabled to false. The first method changes two menus.
Tip: This code disables two menus at once. This adds to simplicity and efficiency in the GUI layer.
DropDownItems is used. Every ToolStripMenuItem has a DropDownItems collection. When there are no sub-items, it is empty. When there are child menus, it contains a collection of them all called a ToolStripItemCollection.
Example 2. You can call the above methods by passing a state bool into them. It is a good idea to name your methods appropriately, and use the correct control names in your program. Otherwise the program will not work.
Tip: You can make menus equal to an expression, such as the Enabled property of a password box.
Example code that uses the above methods: C# void passwordTextBox_EnabledChanged(object sender, EventArgs e) { bool state = passwordTextBox.Enabled; EnableFileToolsMenu(!state); } void ExampleMethod() { // Enable all the items in these menus. EnableFileToolsMenu(true); // Disable the Edit menu. EnableEditMenu(false); }
Summary. You can change the Enabled property on items in a menu. This is a good approach to disabling or enabling all the child menu items in a menu. Or you can pass in the ToolStripMenuItem to a method, and have the method work on that object.