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.
Getting started. 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.
Example program. 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.
Info The CheckedChanged event handler has logic to update the title bar text whenever the user changes the selection of RadioButtons.
And We loop over each sub-control of groupBox1 and groupBox2. When we encounter a RadioButton, we access Checked and Text.
Finally We set the title text of the Window to our findings—this is to show the program is correct.
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;
}
}
}
Groups. 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.
And If more than one (or zero) options can be selected, you should use the CheckBox.
Note The example screenshot is only correct if the user can only have one Pet and only have one Home.
A summary. The RadioButton control provides a user interface for an exclusive selection. We looked at how to use event handlers on RadioButtons.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 9, 2022 (simplify).