Make menu items act like radio buttons in C#

example

This example shows how to make menu items behave like radio buttons in a radio button group. When you select one item, it displays a check mark and the others don’t.


The key is the following CheckMenuItem method.

// Uncheck all menu items in this menu except checked_item.
private void CheckMenuItem(ToolStripMenuItem mnu,
    ToolStripMenuItem checked_item)
{
    // Uncheck the menu items except checked_item.
    foreach (ToolStripItem item in mnu.DropDownItems)
    {
        if (item is ToolStripMenuItem)
        {
            ToolStripMenuItem menu_item =
                item as ToolStripMenuItem;
            menu_item.Checked = (menu_item == checked_item);
        }
    }
}

This method takes as parameters a menu and a menu item. It loops through the objects contained in the menu. If an object is a menu item (e.g. not a separator or something else), the code sets its Checked property appropriately. It sets the property to true for the indicated menu item and false for the other items.

The following code shows how the program uses the CheckMenuItem method.

// Check this menu item and uncheck the others.
private void mnuViewOption_Click(object sender, EventArgs e)
{
    // Check the menu item.
    ToolStripMenuItem item = sender as ToolStripMenuItem;
    CheckMenuItem(mnuView, item);

    // Do something with the menu selection.
    // You could use a switch statement here.
    // This example just displays the menu item's text.
    MessageBox.Show(item.Text);
}

All of the program’s menu items use this same event handler. The code converts the sender that raised the event into a ToolStripMenuItem. It then calls CheckMenuItem.

After that you would add whatever code the program needed to execute for the menu item. This example just displays the item’s text.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in controls, menus, user interface and tagged , , , , , , , , , . Bookmark the permalink.

3 Responses to Make menu items act like radio buttons in C#

  1. Dennis says:

    Very nice – Just a few lines of code

  2. Pingback: Make menu items behave like check boxes in C# -

  3. Tommy says:

    More compact:

    foreach (ToolStripMenuItem item in ((sender as ToolStripMenuItem).OwnerItem as ToolStripMenuItem).DropDownItems)
    {
        item.Checked = (item == (sender as ToolStripMenuItem));
    }

Leave a Reply

Your email address will not be published. Required fields are marked *