Search code examples
c#winformscheckbox

If one checkbox is checked, set the other to unchecked


I have two checkboxes on my form; chkBuried and chkAboveGround. I want to set it up so if one is checked, the other is unchecked. How can I do this?

I have tried the CheckChanged property:

private void chkBuried_CheckedChanged(object sender, EventArgs e)
{
    chkAboveGround.Checked = false;
}
private void chkAboveGround_CheckedChanged(object sender, EventArgs e)
{
    chkBuried.Checked = false;
}

And it works, just not as well as I hoped. That is, when I check chkBuried, then check chkAboveGround, both boxes become unchecked before I can check another one again.


Solution

  • modify your code as below.

    private void chkBuried_CheckedChanged(object sender, EventArgs e)
    {
        chkAboveGround.Checked = !chkBuried.Checked;
    }
    private void chkAboveGround_CheckedChanged(object sender, EventArgs e)
    {
        chkBuried.Checked = !chkAboveGround.Checked;
    }