Search code examples
c#winformsradio-button

C# Winform Radio button behavior


I have 2 radio buttons calling 2 methods on _CheckedChanged event

private void manual_radioBtn_CheckedChanged(object sender, EventArgs e)
        {
            SendDataManual();
        }

private void auto_radioBtn_CheckedChanged(object sender, EventArgs e)
        {
            SendDataAuto();
        }

Now when I check the radiobutton, doesn't matter which one, both functions are being triggered.

When I check manual_radioBtn, both SendDataManual() & SendDataAuto() are being called and if I check auto_radioBtn also, both SendDataManual() & SendDataAuto() are being called.

I know this behaviour won't occur if am using a Click event rather than CheckedChanged. But isn't CheckedChanged the default even for radiobutton.

Is this a normal behavior with radiobuttons or specific behavior when using 2 radiobuttons

What if there are 3 buttons .Will all the methods under the 3 button event trigger at the same time?


Solution

  • The event name gives away it's purpose - CheckedChanged which indicates that the Checked state of the RadioButton has changed. It's not stating that Checked = true (or otherwise), just that the value of it changed.

    From the docs, CheckedChanged:

    Occurs when the value of the Checked property changes.

    One way to handle this is to check the value of the Checked property in your code:

    private void manual_radioBtn_CheckedChanged(object sender, EventArgs e)
    {
        if (manual_radioBtn.Checked)
            SendDataManual();
    }
    
    private void auto_radioBtn_CheckedChanged(object sender, EventArgs e)
    {
        if (auto_radioBtn.Checked)
            SendDataAuto();
    }
    

    My preference would be to handle this in a single function though, something like:

    private void manual_radioBtn_CheckedChanged(object sender, EventArgs e)
    {
        SendData();
    }
    
    private void auto_radioBtn_CheckedChanged(object sender, EventArgs e)
    {
        SendData();
    }
    
    private void SendData()
    {
        if (manual_radioBtn.Checked)
            SendDataManual();
        else if (auto_radioBtn.Checked)
            SendDataAuto();
    }
    

    An advantate of using a single function to handle the response to the event is that you only need one event handler for all of the appropriate CheckedChanged events, rather than one for each RadioButton. That might not seem important when you have two but imagine you have 20 of them.