John V Dole
John V Dole

Reputation: 321

How do I use if statements with checkboxes without clutter

I have this application with 13 checkboxes.
And i want to do if statements to check if a textbox is checked but its going to get really cluttered after checking 4 of them for example

if (checkBox1.IsChecked == true)
    {
          DoSomething();          
    }

else if (checkBox1.IsChecked == true && checkBox2.isChecked = false)
    {
          DoSomething();          
    }

else if (checkBox1.IsChecked == false && checkBox2.isChecked = true)
    {
          DoSomething();          
    }

else if (checkBox1.IsChecked == false && checkBox3.isChecked = true)
    {
          DoSomething();          
    }

else if (checkBox1.IsChecked == false && checkBox3.isChecked = false)
    {
          DoSomething();          
    }


else if (checkBox1.IsChecked == true && checkBox3.isChecked = false)
    {
          DoSomething();          
    }

else if (checkBox1.IsChecked == true && checkBox3.isChecked = true)
    {
          DoSomething();          
    }

I bet you can see the pattern already.. I need to check every possible solution for 13 checkboxes, is there a way to do this more efficiently?

Upvotes: 2

Views: 483

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

13 checkboxes give 213 = 8192 different combinations. Although it is hard to imagine a system that requires end-users to distinguish among so many distinct possibilities, making a program that responds to them is really straightforward.

Assign distinct "tags" from the interval 0..12, inclusive, to each check box. Walk through check boxes, and construct a bit mask from tags of checked boxes, as follows:

var mask = 0;
// Below, comparison == true is required
// because IsChecked is Nullable<bool>
if (checkBox0.IsChecked == true) mask |= 1 << 0;
if (checkBox1.IsChecked == true) mask |= 1 << 1;
if (checkBox2.IsChecked == true) mask |= 1 << 2;
if (checkBox3.IsChecked == true) mask |= 1 << 3;
...
if (checkBox12.IsChecked == true) mask |= 1 << 12;

Now mask has a value from 0 to 8191, inclusive, encoding each distinct combination of check marks. Create an array of 8192 actions corresponding to each combination, and call

action[mask]();

to invoke the action that corresponds to the selected combination.

Upvotes: 6

Related Questions