5

Im trying to create a array of Checkboxes in Winforms and I have four Checkboxes and if I click on a Checkbox, a messagebox should display the checkboxes checked.

 public void checkboxtest()
    {

        CheckBox[] boxes = new CheckBox[4];
        boxes[0] = checkBox1;
        boxes[1] = checkBox2;
        boxes[2] = checkBox3;
        boxes[3] = checkBox4;


        for (int i = 0; i <= 4; i++)
        {

                if (boxes[i].Checked == true && boxes[i].Enabled)
                {
                    MessageBox.Show("boxes[i] is clicked");
                }

        }
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        checkboxtest();
    }

    private void checkBox2_CheckedChanged(object sender, EventArgs e)
    {
        checkboxtest();
    }

continues for 3 and 4 too...

How should I go about it ?? Thanks.

1
  • Why don't use events, You are doing it entirely wrong! Commented Aug 25, 2010 at 6:11

1 Answer 1

3

Your loop termination should be i < 4, not i <= 4 since your array only has 4 elements. Also boxes[i].Checked == true is redundant, you can just say boxes[i].Checked.

If you want to display the checked checkboxes when you toggle the state, you'll need to add an event handler to them (to handle the CheckBox.CheckChanged event):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        _checkBoxes = new CheckBox[] { _checkBox1, _checkBox2, _checkBox3, _checkBox4 };

        foreach (var checkBox in _checkBoxes)
            checkBox.CheckedChanged += new EventHandler(ShowCheckedCheckboxes);
    }

    void ShowCheckedCheckboxes(object sender, EventArgs e)
    {
        string message = string.Empty;

        for (int i = 0; i < _checkBoxes.Length; i++)
        {
            if (_checkBoxes[i].Checked && _checkBoxes[i].Enabled)
            {
                message += string.Format("boxes[{0}] is clicked\n", i);
            }
        }

        MessageBox.Show(message);
    }

    CheckBox[] _checkBoxes;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@ Chris Schmich: thank you so much. What if I need to add a button and then display this 'message' inside 'MessageBox.Show(message);'. So if I click on the button, the messae box should be displayed instead of displaying while I check on a box.
@SLp: I strongly recommend reading about events in Windows Forms: msdn.microsoft.com/en-us/library/1h12f09z.aspx It's well worth your time since events are everywhere in .NET. For your question, though, you should look at the Button.Click event (which is inherited from the Control class): msdn.microsoft.com/en-us/library/…

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.