Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Groupable ToolStripMenuItems

3.50/5 (4 votes)
26 Apr 2007CPOL2 min read 1   548  
ToolStripMenuItems that imitate RadioButton-behaviour.

Screenshot - groupabletoolstripmenuitems.jpg

Introduction

Ever in the need of grouping multiple ToolStripMenuItems together to imitate the behaviour of RadioButtons? This simple control inherits from ToolStripMenuItem and adds a new property for grouping them in Design mode. Multiple groups in the same dropdown menu are supported.

Background

When I was first in the need for ToolStripMenuItems that behave like RadioButtons, I did it via events. The second time, I started to wonder why MS didn't provide an additional property for easily grouping ToolStripMenuItems together. After a little "Googling", I found an example at MSDN: http://msdn2.microsoft.com/en-us/library/ms404318.aspx.

After reading the article, I realized that this wasn't what I was searching for! They explained how to achieve the desired effect with "CheckOnClick" and even provided custom drawing for the radio-button layout. That's not standard (but ugly), and not what I wanted! Furthermore, their example didn't support multiple "groups" in the same dropdown menu.

So I started to implement my own solution. It is based on the example at MSDN, but simplifies it wherever possible.

Using the Code

This section should be named "Using the component".

Add the source file to your project. After a rebuild, you should be able to select ToolStripMenuItemGrouped when designing a ToolStripMenu.

Basically, I just added a simple property called GroupIndex. Its default value is 0, which means: no group. For all ToolStripMenuItemGrouped that belong together, enter a value greater than that. By using different values, it is possible to support more than one group in the same dropdown menu.

Points of Interest

I left the overridden enabled property of the original sample code by MS. That added the possibility to automatically enable/disable all ToolStripMenuItemGrouped subitems when the owner control (ToolStripMenuItem) changed its checked-state. You can try it out by adding ToolStripMenuItemGrouped items to the dropdown of a ToolStripMenuItem. Then set the CheckOnClick property of the owner to "true". At runtime, the subitems will automatically change their enabled state, whether the owner is checked or not.

To add the new class to the designer, I simply had to provide the following attribute:

C#
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ContextMenuStrip)]

Further Reading

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)