Building an array from a series of CheckBox controls

I have a small problem regarding arrays.

This is the code:

char[] select = new char[] { '+', '-', '/', '%' };
var rand = new Random();
char num = select[rand.Next(5)];

I have five CheckBox controls. If my control named checkboxadd is checked, I want the array to have the value of { + }. And if my controls named checkboxadd and checkboxsubtract are checked, I want the value of the array to change to { +, - }. And so on.

Is this possible?

More: I am creating a Windows Forms application. The application is an arithmetic learning system which offers a set of operations which are selected via CheckBox controls. I think my approach is wrong...can anyone help?

Upvotes: 0

Views: 1468

Answers (1)

CSharper
CSharper

Reputation: 534

You add your checkboxes in the Designer (so they are created in the InitializeComponent() call). After that you initialize a helper Array that allows elegant coding in the CheckedChanged event handler. So you react on every change in a checked state:

public partial class Form1 : Form {
    private CheckBox[] checkboxes;
    private char[] operators;

    public Form1() {
        InitializeComponent();
        checkboxes = new[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
        checkBox1.Tag = '+';
        checkBox2.Tag = '-';
        checkBox3.Tag = '*';
        checkBox4.Tag = '/';
        checkBox5.Tag = '%';
        foreach (var cb in checkboxes) {
            cb.CheckedChanged += checkBox_CheckedChanged;
        }
    }

    private void checkBox_CheckedChanged(object sender, EventArgs e) {
        operators = checkboxes.Where(cb => cb.Checked)
            .Select(cb => cb.Tag)
            .Cast<char>()
            .ToArray();
    }
}

Upvotes: 2

Related Questions