Need some help with looping

Joined
May 10, 2013
Messages
321
Reaction score
59
Ok, so I'm trying to learn C# as I find it interesting. But I came across a little thing.
Here's the code I have now:

Code:
string movies = "";

if (checkBox1.Checked)
{
	movies += checkBox1.Text + "\r\n";
}
if (checkBox2.Checked)
{
	movies += checkBox2.Text + "\r\n";
}
if (checkBox3.Checked)
{
	movies += checkBox3.Text + "\r\n";
}
if (checkBox4.Checked)
{
	movies += checkBox4.Text + "\r\n";
}
if (checkBox5.Checked)
{
	movies += checkBox5.Text + "\r\n";
}


MessageBox.Show(movies);

How to make it like this but now in C#?:

Code:
for (int i = 1; i <= 5; i++) {
    if (checkBox[i].Checked) {
        movies += checkBox[i].Text + "\r\n";
    }
}

MessageBox.Show(movies);

Obvious the last code doesn't work. I need to know how to apply this method. Anyone can help?

Thanks.
 
Let me give you a hint, the second piece of code iterates through the checkboxes like this:

checkBox[1].Checked
checkBox[2].Checked
checkBox[3].Checked
checkBox[4].Checked
checkBox[5].Checked
 
Yes, I know. That's the point. I don't know how to loop it correctly and without the []. If I do this:

Code:
for (int i = 1; i <= 5; i++) {
	if (checkBox+i.Checked) {
	movies += checkBox+i.Text + "\r\n";
	}
}

It doesn't work and Visual underlines checkBox and Checked in red.
"The name checkBox does not exist in the current context"
 
Code:
foreach (Control c in this.Controls)
{
    if (c is CheckBox && ((CheckBox)c).Checked)
    {
        movies += c.Text + "\r\n";
    }
}


That should do what you want.
 
Back