Parteek Singh Bedi
Parteek Singh Bedi

Reputation: 101

Initialize array for storing labels

In my program, I have already made 10 labels in designing window and they are labelled as label 1, label 2,... and so on. I wanna perform some operation all these labels at once so I made an array to store these labels and then perform operation on array, as it will be easier to apply loop. Can we apply loop to store these labels in to array, because if the labels are 50, it will be tougher to follow this strategy

Label[] labelArray = new Label[10];
labelArray[0] = label1;
labelArray[1] = label2;
labelArray[2] = label3;
labelArray[3] = label4;
labelArray[4] = label5;
labelArray[5] = label6;
labelArray[6] = label7;
labelArray[7] = label8;
labelArray[8] = label9;

Upvotes: 1

Views: 516

Answers (2)

Benjamin RD
Benjamin RD

Reputation: 12034

For Windows Forms you can use:

List<Label> lbls = this.Controls.OfType<Label>().ToList();

and now, you have all your lables in a list.

You can get them by

foreach(var lbl in lbls){
    //var value = lbl.Text;
}

Upvotes: 0

John Wu
John Wu

Reputation: 52210

If the labels of interest all have something in common, e.g. they all have "label" in the name, or they have the same Tag (which would be a good property to use for this purpose), then you could simply use

//using System.Linq;
var list = this.Controls.OfType<Label>().Where
( 
    label => label.Name.Contains("label")     //Use these, or any other
          && label.Tag == "MyUniqueTag"       //properties, to find what you need
);
foreach (var label in list)
{
    DoSomething(label);
}

Also, see this related question.

Upvotes: 2

Related Questions