user2461116
user2461116

Reputation: 19

CheckBox in C# Windows App

I have 3 checkboxes and I am able to turn two of them off if one is checked. But I want that if the 3rd one is checked then the first two should be turned off. how can I do that?

This is what I am trying.

private void chkResFoodVeg_CheckedChanged(object sender, EventArgs e)
{
    //disables the other checkbox if one is checked
    this.chkResFoodNveg.Enabled = !this.chkResFoodVeg.Checked;
}

private void chkResFoodNveg_CheckedChanged(object sender, EventArgs e)
{
    this.chkResFoodVeg.Enabled = !this.chkResFoodNveg.Checked;
}

private void chkResFoodBoth_CheckedChanged(object sender, EventArgs e)
{
    this.chkResFoodBoth.Enabled = !this.chkResFoodNveg.Checked &&
   !this.chkResFoodVeg.Checked;
}

The last part of code doesn't work. It should turn off the first two checkboxes.

Thanks

Upvotes: 0

Views: 825

Answers (2)

Derek W
Derek W

Reputation: 10026

Looks like a job for the RadioButton! Although it is possible to implement what you want using the CheckBox - it's likely the wrong tool for this job.

Adding these to a Windows Form automatically implements the functionality that you want as long as they belong to the same container object like a GroupBox or Panel.

Example of Radio Buttons in use

Upvotes: 1

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

Your logic is backwards, you need two assignments not combine the inputs.

private void chkResFoodBoth_CheckedChanged(object sender, EventArgs e)
{
    this.chkResFoodNveg.Enabled = !this.chkResFoodBot.Checked;
    this.chkResFoodVeg.Enabled = !this.chkResFoodBot.Checked;
}

However, from how you are describing your buttons actions, it sounds like you are trying to emulate the behavior of a RadioButton, perhaps you should use that instead. It will only let you choose one of the 3 options at a time.

enter image description here

Upvotes: 1

Related Questions