innuendomaximus
innuendomaximus

Reputation: 353

Get if any RadioButton in a Groupbox was checked

I have a Windows Forms application, where I have several radio buttons stored in a GroupBox. I need to enable a different GroupBox based on the selected radio button.

groubBox.Enter doesn't seem to be the EventHandler I was looking for. Is there any way to do it my way or do I have to create a handler for each radiobutton.CheckedChanged?

Edit

The workflow of the application is:

A file gets selected → The GroupBox gets enabled → A Panel/ComboBox, TextBox gets enabled depending on the selected RadioButton

Upvotes: 1

Views: 14005

Answers (2)

Fabio
Fabio

Reputation: 32443

Create CheckedChanged event handler, one for all radiobuttons
Set RadioButton.Tag to reference the GroupBox it respondent for

For example in the constructor

public YourForm()
{
    radioButton1.Tag = groupBox1;
    radioButton2.Tag = groupBox2;
    radioButton3.Tag = groupBox3;

    radioButton1.CheckedChanged += radioButtons_CheckedChanged;
    radioButton2.CheckedChanged += radioButtons_CheckedChanged;
    radioButton3.CheckedChanged += radioButtons_CheckedChanged;
}

void radioButtons_CheckedChanged(object sender, EventArgs e)
{
    RadioButton button = sender as RadioButton;
    if (button == null) return;

    GroupBox box = button.Tag as GroupBox
    if (box == null) return;

    box.Enabled = button.Checked;
}

Enabling GroupBox will enable all child controls in it

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29036

Let gbRadioButtons be the name of the GroupBox, Then you can iterate though each radioButton in that particular Groupbox and check whether it is selected or not by using the following code(include this code where you want to check):

bool isAnyRadioButtonChecked = false;
foreach (RadioButton rdo in gbRadioButtons.Controls.OfType<RadioButton>())
{
    if (rdo.Checked)
    {
        isAnyRadioButtonChecked=true;
        break;
    }
}
if (isAnyRadioButtonChecked)
{ 
  // Code here one button is checked
}
else
{
  // Print message no button is selected 
}

Upvotes: 1

Related Questions