Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio button checked changed event fires twice

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?

like image 493
Muhammad Ali Dildar Avatar asked Jul 15 '12 16:07

Muhammad Ali Dildar


4 Answers

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);         }     } } 
like image 116
David Hall Avatar answered Sep 26 '22 23:09

David Hall


To avoid it, just check if radioButton is checked

for example:

private void radioButton1_CheckedChanged(object sender, EventArgs e) {     if (radioButton1.Checked)         //your code } 
like image 28
jaleel Avatar answered Sep 22 '22 23:09

jaleel


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).

like image 30
kmatyaszek Avatar answered Sep 25 '22 23:09

kmatyaszek


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)

like image 42
Rafael Dowling Goodman Avatar answered Sep 24 '22 23:09

Rafael Dowling Goodman