Okey, so what I'm trying to do is to set about 5 labels to visible using a for loop.

int nr_bokstaver = slutt_losning.Length;
for (int index = 0; index <= nr_bokstaver; index++)
{
        label+index.Visible = true;
}

I want the name of the label to change according to the value of the index of the for loop, but I just can't seem to do it.

This will loop through all of the form's controls searching for the name of the control....

private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 1; i <= 3; i++)
                foreach (Control c in this.Controls)
                    if (c.Name == "label" + i)
                        c.Visible = true;
        }

This worked really well, but could you explain what this is exactly doing? I realize it's a foreach loop, but everything else is sort of confusing.

Sorry for asking, but I wanna learn instead of copying and pasting :)

Comments
exactly the kind of attitude i like to see, if something confuses you, ALWAYS ask :)

No problem. The foreach loop is iterating through the form's control list, which is maintained by the designer every time you add or remove controls to/from your form. Then, we are checking the name of the control (c.Name) to find the labels: label1 - label3, based on what you said you would like. If the label control's name matches the current control, then we are setting it's Visible property (c.Visible) to true.

Edited 7 Years Ago by DdoubleD: n/a

Comments
a good answer and a clear explaination :)

If you look inside the form's designer.cs file using the view code option in Solution Explorer, you will find somthing similar to the following, which is where it adds those label controls to the Controls list:

this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);

An excellent explaination DdoubleD :) And a great attitude from CyberPirate1. So many people paste the code, see that it works and move on. Its great to see someone stop to say "great, it works...but why does it work?". That attitude will serve you well as a coder :)
Oh, and welcome to Daniweb. Please remember to mark the thread as solved sicne your question has been answered.

This article has been dead for over six months. Start a new discussion instead.