Make menu items act like radio buttons in C#


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.

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.

7 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));
  4. Pingback: Is there a Unicode “white space” character that is exempt from trimming? | ASK Dev Archives

  5. Ello says:

    Compact and Readable:

        .SelectMany(toolStripMenuItem => toolStripMenuItem.DropDownItems.OfType())
        .ForEach(toolStripMenuItem =>
            toolStripMenuItem.Checked = toolStripMenuItem == (ToolStripMenuItem)sender;
  6. shahab taheri says:

    very usefule

Comments are closed.