0

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?

3
  • 2
    select is a reserved keyword. You should escape it using @select or use a different name for the variable. Commented Nov 24, 2012 at 17:27
  • 2
    Your code sample and your question don't make sense together. Why are you selecting a random element in your array, and what does that have to do with checkboxes? Commented Nov 24, 2012 at 18:10
  • 1
    Also, what version of .NET are you using? There are easier ways to do this on newer versions, if I understand your question correctly, which I'm not 100% sure I do. Commented Nov 24, 2012 at 18:11

1 Answer 1

2

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The methods Where, Select, Cast and ToArray are defined in the Enumerable class which is the basis for LINQ.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.