C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: By using this nesting strategy, you can have multiple groups of RadioButtons on a single form.
Tip 2: You may want to add the CheckedChanged event handler on your RadioButtons.
Also: You can actually have all the RadioButtons point to the same CheckedChanged event handler using the event window in Visual Studio.
Example RadioButton program: C#
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;
}
}
}
Info: The radioButton1_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 correctly works.
Note: The example screenshot is only correct if the user can only have one Pet and only have one Home.
Also: For animal lovers or people who are wealthy and own many homes, the dialog would not be sufficient.
And: We discussed, conceptually, the use of RadioButtons and also their grouping behavior.