Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
804 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...