I have 4 check boxes. One or all can be selected for the program to do its thing. Right now I only have if statements for when only one of them is selected. if I were to do if statements for all situations, I will need 24. Is there an easier way?
You can use an Enum
to hold the checked values
[Flags]
enum BoxesChecked
{ None = 0, First = 1, Second = 2, Third = 4, Fourth = 8 }
...
var boxesChecked = BoxesChecked.None;
if (box1.Checked)
boxesChecked |= BoxesChecked.First;
Then make a map of associated actions and retrieve the one that you need based on the given combination
var actionsMap = new Dictionary<BoxesChecked, Action>
{
{ BoxesChecked.First | BoxesChecked.Second, DoSomething },
{ BoxesChecked.Second | BoxesChecked.Fourth, DoSomethingElse },
...
};
var action = actionsMap[boxesChecked];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.