Radio button checked changed event fires twice

Viewed 74564

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?

8 Answers

The other answers are correct but miss the reason for the underlying problem. When a radio button is checked the first event sent is the change from the unchecked item however if you check its state by its control name you will still see its old checked status because the form has not been updated yet. To see its true status you need to cast the sender object. This allows you to perform any actions relating to the condition which is being deselected should you need to do so.

In the not uncommon scenario below multiple radio buttons are sent to the same handler event. Simply checking the state of the sender for checked will not work here as we need to perform different actions depending on which radio button has been pressed. So first we ignore any sender that has just been unchecked. then we identify the checked sender by control name to process the correct action.

private void ModeChangedExample(object sender, EventArgs e)
{
    // multiple radio buttons come here
    // We only want to process the checked item.
    // if you need to something based on the item which was just unchecked don't use this technique. 
    // The state of the sender has not been updated yet in the form.
    // so checking against rdo_A check state will still show it as checked even if it has just been unchecked
    // only the sender variable is up to date at this point.
        
    // To prevent processing the item which has just been uncheked
    RadioButton RD = sender as RadioButton;
    if (RD.Checked == false) return;

    if (rdo_A.Name == RD.Name)
    {
        //Do stuff
    }

    if (rdo_B..Name == RD.Name)
    {
        // Do other stuff
    }

    if (rdo_C.Name == RD.Name)
    {
        // Do something else
    }

}

This problem of double checking happens when there is a series of RadioButton Clicks in succession.I had this same problem.The last click will give two results.To overcome this i made a dummy click in the end.The double click stopped.Try this method. Venkatraman

Related