Chapter 4 Readings: 4.9 Radio Buttons and Check Boxes
Overview of Radio Buttons and Check Boxes
Graphical User Interfaces (GUIs) commonly utilize radio buttons and check boxes to allow users to select items or options within an application interface.
The RadioButton Control
Radio buttons are useful when the user must select exactly one choice from a set of several mutually exclusive choices.
Visual Appearance and States
A radio button consists of a small circle accompanied by text.
Selected State: The small circle appears filled in.
Deselected State: The small circle appears empty.
Example (Figure 4-24): A form displaying three options—Coffee, Tea, and Soft Drink. When Coffee is selected, its circle is filled, while the circles for Tea and Soft Drink remain empty.
Mutually Exclusive Selection
At run time, only one radio button in a given group can be selected at a time.
Clicking an unselected radio button selects it and automatically deselects whichever radio button was previously selected in that group.
This behavior is termed mutually exclusive selection.
Etymology
The name "radio button" originates from mechanical car radios of the past, which featured physical push buttons for selecting radio stations. Pushing one station button physically popped out the currently selected button, ensuring only one station was active at any given moment.
Creating Radio Buttons and Grouping Controls
To create radio buttons on a Windows Form, use the RadioButton control, located in the Common Controls section of the Visual Studio Toolbox.
RadioButton controls are organized into groups using one of three structural arrangements:
Inside a
GroupBoxControl: AllRadioButtoncontrols placed inside aGroupBoxbelong to the same group.Inside a
PanelControl: AllRadioButtoncontrols placed inside aPanelbelong to the same group.Directly on the Form: All
RadioButtoncontrols placed directly on a form (and not nested inside aGroupBoxorPanel) belong to the same group.
Multiple Groups Example (Figure 4-25)
A form can host multiple independent groups of radio buttons simultaneously.
For example, a form containing a
GroupBoxcontrol on the left (with drink options like Coffee) and aPanelcontrol on the right (with meal options like Lunch) allows the user to select one item from the left group and one item from the right group independently.
RadioButton Control Properties
The Text Property
Holds the string displayed alongside the radio button's circle.
Example: Setting the
Textproperties toCoffee,Tea, andSoft Drinklabels the respective options for the user.
The Checked Property
A Boolean property (
TrueorFalse) that determines whether the control is selected or deselected.True: The radio button is selected.False: The radio button is deselected.
Default Value:
False.Behavior in Properties Window: Setting the
Checkedproperty of a singleRadioButtontoTruein the Properties window automatically resets theCheckedproperties of all otherRadioButtoncontrols within that same group toFalse.
Rules for Default Selection
When designing a group of
RadioButtoncontrols, always explicitly set theCheckedproperty of one control toTruein the Properties window.Automatic Fallback: If all
RadioButtoncontrols in a group are left withCheckedset toFalse, the control with the lowestTabIndexvalue will automatically have itsCheckedproperty set toTruewhen the application executes.
Programming Radio Buttons in Code
Evaluating the Checked Property
In code, the state of a RadioButton control is determined by evaluating its Boolean Checked property in a conditional structure.
Single Radio Button Evaluation
To test if a RadioButton named choice1RadioButton is selected:
if (choice1RadioButton.Checked)
{
MessageBox.Show("You selected Choice 1");
}
Note: It is not necessary to explicitly compare the property against true using the equality operator (==). The code above is functionally identical to:
if (choice1RadioButton.Checked == true)
{
MessageBox.Show("You selected Choice 1.");
}
Evaluating Multiple Radio Buttons
When evaluating a group of radio buttons, an if...else if chain ensures that only the block corresponding to the selected option executes.
Example Project: RadioButton
Location:
Chap04folder of the Student Sample Programs.Form Design (Figure 4-26): Options for Football, Basketball, and Baseball, along with an OK button.
okButton_Click Event Handler Code:
1 private void okButton_Click(object sender, EventArgs e)
2 {
3 if (footballRadioButton.Checked)
4 {
5 MessageBox.Show("You selected Football.");
6 }
7 else if (basketballRadioButton.Checked)
8 {
9 MessageBox.Show("You selected Basketball.");
10 }
11 else if (baseballRadioButton.Checked)
12 {
13 MessageBox.Show("You selected Baseball.");
14 }
15 }
Code Execution Details:
Line 3: Evaluates whether
footballRadioButton.Checkedistrue.Line 5: If
true, displays a message box with"You selected Football.".Line 7: If
footballRadioButton.Checkedisfalse, evaluates whetherbasketballRadioButton.Checkedistrue.Line 9: If
true, displays a message box with"You selected Basketball.".Line 11: If
basketballRadioButton.Checkedisfalse, evaluates whetherbaseballRadioButton.Checkedistrue.Line 13: If
true, displays a message box with"You selected Baseball.".
The CheckBox Control
Visual Appearance and Interaction
Appears as a small square box accompanied by text.
Behavior: Clicking an empty check box places a check mark inside it (selecting it). Clicking a checked box removes the check mark (deselecting it).
Key Distinction from Radio Buttons
Unlike radio buttons, check boxes are not mutually exclusive.
A group of check boxes allows any number of options (zero, one, or multiple) to be selected simultaneously.
Created using the
CheckBoxcontrol found in the Common Controls section of the Toolbox.
CheckBox Control Properties and Code Integration
The Text Property
Holds the text displayed adjacent to the square box (e.g., setting
TexttoPepperoni).
The Checked Property
A Boolean property (
TrueorFalse).True: Check box is checked/selected.False: Check box is unchecked/deselected.
Code Structure for Multiple Check Boxes
Because check boxes permit multiple independent selections, code evaluating check box states typically uses separate independent if statements rather than an if...else if construct.
Basic Conditional Structure
if (option1CheckBox.Checked)
{
MessageBox.Show("You selected Option 1.");
}
Example Project: CheckBox Example
Location:
Chap04folder of the Student Sample Programs.Form Design (Figure 4-28): Options for Pepperoni, Cheese, and Anchovies, with an OK button.
okButton_Click Event Handler Code:
1 private void okButton_Click(object sender, EventArgs e)
2 {
3 if (pepperoniCheckBox.Checked)
4 {
5 MessageBox.Show("You selected Pepperoni.");
6 }
7
8 if (cheeseCheckBox.Checked)
9 {
10 MessageBox.Show("You selected Cheese.");
11 }
12
13 if (anchoviesCheckBox.Checked)
14 {
15 MessageBox.Show("You selected Anchovies.");
16 }
17 }
Code Execution Details:
Lines 3–6: Independent
ifstatement checkingpepperoniCheckBox.Checked. Displays message if selected.Lines 8–11: Independent
ifstatement checkingcheeseCheckBox.Checked. Displays message if selected.Lines 13–16: Independent
ifstatement checkinganchoviesCheckBox.Checked. Displays message if selected.Result: If multiple check boxes are selected, multiple message boxes appear sequentially.
The CheckedChanged Event
Trigger: Fires whenever the
Checkedproperty of aRadioButtonorCheckBoxcontrol changes (either fromFalsetoTrueor fromTruetoFalse).Purpose: Used to perform immediate actions upon selection or deselection without requiring the user to click a separate command button.
Creation Method: Double-click the
RadioButtonorCheckBoxcontrol in the Visual Studio Designer. This automatically generates an emptyCheckedChangedevent handler stub in the code editor.
Tutorial 4-5: Creating the Color Theme Application
This tutorial demonstrates using RadioButton controls and CheckedChanged event handlers to immediately change a form's background color when a radio button is selected.
Step-by-Step Procedure
Create Project: Start Visual Studio and open a new Windows Forms Application project named
Color Theme.Set Up Form: Set the form's
Textproperty toColor Theme. Place controls according to Table 4-8.Yellow RadioButton Handler: Double-click
yellowRadioButtonin the Designer to generateyellowRadioButton_CheckedChanged. Insert code from lines 22–25 of Program 4-5.Red RadioButton Handler: Double-click
redRadioButtonin the Designer to generateredRadioButton_CheckedChanged. Insert code from lines 30–33 of Program 4-5.White RadioButton Handler: Double-click
whiteRadioButtonin the Designer to generatewhiteRadioButton_CheckedChanged. Insert code from lines 38–41 of Program 4-5.Normal RadioButton Handler: Double-click
normalRadioButtonin the Designer to generatenormalRadioButton_CheckedChanged. Insert code from lines 46–49 of Program 4-5.Exit Button Handler: Double-click
exitButtonin the Designer to generateexitButton_Click. Insert code from lines 54–55 of Program 4-5.Save and Run: Run the application. Verify that
normalRadioButtonis selected by default (Checked = True). Test clicking each radio button to verify immediate background color changes, then click Exit to close.
Control Property Settings (Table 4-8)
Control Name | Control Type | Property Settings |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complete Source Code (Program 4-5)
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Color_Theme
12 {
13 public partial class Form1 : Form
14 {
15 public Form1()
16 {
17 InitializeComponent();
18 }
19
20 private void yellowRadioButton_CheckedChanged(object sender, EventArgs e)
21 {
22 if (yellowRadioButton.Checked)
23 {
24 this.BackColor = Color.Yellow;
25 }
26 }
27
28 private void redRadioButton_CheckedChanged(object sender, EventArgs e)
29 {
30 if (redRadioButton.Checked)
31 {
32 this.BackColor = Color.Red;
33 }
34 }
35
36 private void whiteRadioButton_CheckedChanged(object sender, EventArgs e)
37 {
38 if (whiteRadioButton.Checked)
39 {
40 this.BackColor = Color.White;
41 }
42 }
43
44 private void normalRadioButton_CheckedChanged(object sender, EventArgs e)
45 {
46 if (normalRadioButton.Checked)
47 {
48 this.BackColor = SystemColors.Control;
49 }
50 }
51
52 private void exitButton_Click(object sender, EventArgs e)
53 {
54 // Close the form.
55 this.Close();
56 }
57 }
58 }
Checkpoint Questions & Reference Answers
Checkpoint 4.26
Question: If several
RadioButtoncontrols have been created in the sameGroupBox, how many of them may be selected at one time?Answer: Exactly one
RadioButtoncontrol may be selected at a time within a singleGroupBoxcontainer, due to mutually exclusive selection.
Checkpoint 4.27
Question: If several
CheckBoxcontrols have been created in the sameGroupBox, how many of them may be selected at one time?Answer: Any number of
CheckBoxcontrols (ranging from zero to all of them) may be selected simultaneously, as check boxes are not mutually exclusive.
Checkpoint 4.28
Question: In code, how do you determine whether a
RadioButtonor aCheckBoxcontrol has been selected?Answer: By testing the Boolean value stored in the control's
Checkedproperty (e.g., using anifstatement such asif (myControl.Checked)).