Radio button checked changed event fires twice

71,864

Solution 1

As the other answerers rightly say, the event is fired twice because whenever one RadioButton within a group is checked another will be unchecked - therefore the checked changed event will fire twice.

To only do any work within this event for the RadioButton which has just been selected you can look at the sender object, doing something like this:

void radioButtons_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = sender as RadioButton;
    if (rb != null)
    {
        if (rb.Checked)
        {
            // Only one radio button will be checked
            Console.WriteLine("Changed: " + rb.Name);
        }
    }
}

Solution 2

To avoid it, just check if radioButton is checked

for example:

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    if (radioButton1.Checked)
        //your code
}

Solution 3

CheckedChanged is raised whenever the Checked property changes. If you select a RadioButton then the previously selected RadioButton is unchecked (fired CheckedChanged), and then the new RadioButton is checked (fired CheckedChanged).

Solution 4

It's triggering once for the radio button transition from checked to unchecked, and again for the radio button transitioning from unchecked to checked (i.e. any change in checked state triggers the event)

Share:
71,864
Muhammad Ali Dildar
Author by

Muhammad Ali Dildar

Student

Updated on June 09, 2021

Comments

  • Muhammad Ali Dildar
    Muhammad Ali Dildar about 3 years

    Please read my question its not a duplicate one.

    I've three radio buttons on windows form and all these buttons have common 'CheckedChanged' event associated. When I click any of these radio buttons, it triggers the 'CheckedChanged' event twice.

    Here is my code:

    private void radioButtons_CheckedChanged(object sender, EventArgs e)
    {
        //My Code
    }
    

    I inserted the breakpoint and the whole code within this event iterates twice. Please tell me why it is behaving like this?

  • Muhammad Ali Dildar
    Muhammad Ali Dildar almost 12 years
    Don't you thin 'if (rb != null)' is unnecessary?
  • David Hall
    David Hall almost 12 years
    @MuhammadAliDildar It avoids any chance of a null reference exception here - of course since you wire up all the events, you can be pretty sure that this event handler will only be attached to a radiobutton, but the 'best practice' way of doing things is to check that the cast worked. Then again - from a certain point of view throwing an exception when you attach the event handler incorrectly may be preferable so you can fix the code.
  • Admin
    Admin almost 8 years
    @davidkonrad real code should never need any explanation! Doh!
  • codeMonkey
    codeMonkey about 3 years
    This appears to be true for Windows Forms but not for WebForms.