RadioButton
This allows distinct selection of several items. In each group of RadioButtons
, only one can be checked. Conceptually, this control implements an exclusive selection.
You should make a new Windows Forms application in Visual Studio. Then you can add GroupBox
(or Panel) controls to it—these can contain RadioButtons
.
Here we set the CheckedChanged
handler on all Radiobuttons to the same event handler. It is possible for multiple controls to use the same event handler.
CheckedChanged
event handler has logic to update the title bar text whenever the user changes the selection of RadioButtons
.groupBox1
and groupBox2
. When we encounter a RadioButton
, we access Checked and Text.using System; using System.Windows.Forms; namespace WindowsFormsApplication11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { // Executed when any radio button is changed. // ... It is wired up to every single radio button. // Search for first radio button in GroupBox. string result1 = null; foreach (Control control in this.groupBox1.Controls) { if (control is RadioButton) { RadioButton radio = control as RadioButton; if (radio.Checked) { result1 = radio.Text; } } } // Search second GroupBox. string result2 = null; foreach (Control control in this.groupBox2.Controls) { if (control is RadioButton) { RadioButton radio = control as RadioButton; if (radio.Checked) { result2 = radio.Text; } } } this.Text = result1 + " " + result2; } } }
RadioButtons
are grouped according to their enclosing control. To create multiple groups of RadioButtons
, add containers such as Panel or GroupBox
and then put RadioButtons
inside.
RadioButton
, CheckBox
So when should you use a RadioButton
as opposed to a CheckBox
? If only one option can be logically selected, then you should use a RadioButton
.
CheckBox
.The RadioButton
control provides a user interface for an exclusive selection. We looked at how to use event handlers on RadioButtons
.