Reputation: 7218
I am making a wpf form where there is a question and user will select yes or no checkbox. Now I need to put few conditions so that:
1. User has to select YES or NO, which means the question cannot be left empty
2. User cannot select both YES or NO, which means only YES or NO has to be selected
3. If user selects YES, then save the option and proceed further
4. If user selects NO, then save the option and proceed further
Now for this what I am doing is:
//Just for the tesing purpose, I am using message box to show what user has selected
//If user has selected YES
if (yes.IsChecked == true)
{
MessageBox.Show(" Yes checked");
}
//If user has selected NO
if (no.IsChecked == true)
{
MessageBox.Show("No checked");
}
//If user has not selected any option
if (yes.IsChecked == false && no.IsChecked == false)
{
MessageBox.Show("please select option");
}
//If user has selected both the options
if (yes.IsChecked == true && no.IsChecked == true)
{
MessageBox.Show("cannot select both options");
}
This is not working as expected because if user selects both the check boxes, then it shows
Yes checked, then
No checked, then
cannot select both options
Which is the best method to accomplish above conditions.?
Upvotes: 0
Views: 71
Reputation: 2835
You only have to Rearrange your if conditions
//If user has not selected any option
if (yes.IsChecked == false && no.IsChecked == false)
{
MessageBox.Show("please select option");
}
//If user has selected both the options
else if (yes.IsChecked == true && no.IsChecked == true)
{
MessageBox.Show("cannot select both options");
}
//If user has selected YES
else if (yes.IsChecked == true)
{
MessageBox.Show(" Yes checked");
}
//If user has selected NO
else if (no.IsChecked == true)
{
MessageBox.Show("No checked");
}
Upvotes: 0
Reputation: 1
You could combine the tests with the ^ operator:
if (yes.IsChecked ^ no.IsChecked)
{
// proceed, as exactly one is checked
}
Optionally you can test if both are checked:
if (yes.IsChecked && no.IsChecked)
{
MessageBox.Show("cannot select both options");
}
And as last option you can test if both are unchecked:
if (!yes.IsChecked && !no.IsChecked)
{
MessageBox.Show("please select option");
}
Upvotes: 0
Reputation: 77
In an OR situation you should use a radio button not a check box. It removes the need for you to write your own validation method to check for both being selected as only one at a time is possible, you then only need to check that something has been selected and just save that selection.
Upvotes: 2
Reputation: 2912
Could you just force the other option clear if one box is checked?
//If user has selected YES
if (yes.IsChecked == true)
{
MessageBox.Show(" Yes checked");
// Ensure that 'no' is not checked
no.IsChecked = false;
}
//If user has selected NO
if (no.IsChecked == true)
{
MessageBox.Show("No checked");
// Ensure that 'yes' is not checked
yes.IsChecked = false;
}
Upvotes: 0