views:

31

answers:

3

Let's say I have

Label1
Label2
Label3

I want to do something like:

for(int i=0;i<3;i++)
{
    LabelArray[i].Text = "weee!";
}

To populate the array, I know I can do something like:

LabelArray[0] = Label1;
LabelArray[1] = Label2;
LabelArray[2] = Label3;

But that doesn't seem smart just because I have 50 labels, and that would be 50 silly lines of code.

Is there a better way to do this?

Thanks!

A: 

If you create the labels programatically, you can create the label, and set the text inside the for loop, then add it to the forms Controls collection.

If you add 50 labels at design time so they get 50 individual names, then I don't know about any better solution.

If you want to set the text of all labels, you can also iterate the Controls collection of your Form and check if they are of type Label, and in case they are, set their text property.

Øyvind Bråthen
A: 

You have two options:

  • Use Reflection to get the labels, e.g.

    for (int i = 0; i < 50; i++)
        labelArray[i] = (Label)GetType().GetField("Label" + (i+1)).GetValue(this);
    
  • Don’t use the WinForms designer to create the 50 labels, but create them dynamically and put them straight into the array in the first place.

Timwi
Your reflection code is not working, but I don't know how to fix it. Specifically "GetType()" and "this" are flagged for errors.
Soo
Ok, these errors seem to be stemming from the fact that the code is inside of a static method....
Soo
@Soo: Correct. If the set of labels never changes during runtime, you can put this in the constructor of your form, for example.
Timwi
+2  A: 

You have to iterate through Form.Controls[] to find Labels.

foreach (var control in this.Controls)
{
    if (control is Lable)
         labelList.Add((Lable)control));
}
Orsol