PrinceOfBorgo
PrinceOfBorgo

Reputation: 592

Fire event programmatically C#

I have several radio buttons inside a container. For each one I have the CheckedChangedevent so I have a code like this

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    if ((sender as RadioButton).Checked)
    // do stuff...
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
    if ((sender as RadioButton).Checked)
    // do stuff...
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
    if ((sender as RadioButton).Checked)
    // do stuff...
}
// ... and so on...

Then I must fire the CheckedChanged event for the currently checked radioButton. To get the radioButton I used this code:

RadioButton checkedButton = container.Controls.OfType<RadioButton>()
                            .FirstOrDefault(r => r.Checked);

Now how can I fire the CheckedChanged event for checkedButton?

EDIT: I'm using WinForms. My radio buttons are in a tabPage. When I open the tabPage I need to know what is the currently checked radioButton and fire the corresponding checkedChanged event. This is because when I select another tabPage I perform other actions and, going back to the tabPage containing the radio buttons, I need to restore the previous state.

Upvotes: 1

Views: 5059

Answers (1)

mm8
mm8

Reputation: 169400

Changing the value of the Checked property should fire the event:

checkedButton .Checked = !checkedButton .Checked;

You may also call the event handler explicitly, e.g.:

RadioButton checkedButton = container.Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked);
switch (checkedButton.Name)
{
    case "radioButton1":
        radioButton1_CheckedChanged(this, EventArgs.Empty);
        break;
    case "radioButton2":
        radioButton2_CheckedChanged(this, EventArgs.Empty);
        break;
    case "radioButton3":
        radioButton3_CheckedChanged(this, EventArgs.Empty);
        break;
}

Depending on your requirements, you may of course want to consider using the same event handler for all RadioButtons.

Upvotes: 2

Related Questions