[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.