How to demand multi objects by for loop

Viewed 54

I wish you a nice day I have a number of labels inside windows form, for example with these names label1, labels2, label3, labels4 ... and so on

How to create a for loop to make changes to all or some of them properties according to a condition that depends on the number inside the label name

My respects

3 Answers

You can use the Label.Text property on each label to get and set the text on them.

To iterate through them just place them into a an array or list.

For example we can do

private Label label1;
private Label label2;
private Label label3;

void DoSomethingWithLabels()
{
    Label[] labels = { label1, label2, label3};
    
    foreach(var item in labels)
    {
        if(item.Text == "SomeText")
        {
             // do something
        }
        else
        {
             item.Text = "Hello World!";
        }
    }
}

Try this

        Label[] teste = { label1, label2, label3, label4 };

        foreach(var label in teste)
        {
            label.Text = "ALTERED";
        }

Assuming it's Windows Forms, and assuming the label names all start as "label", you can use the Form.Controls index property to get the labels. So you could loop like this:

for (int i = 1; i <= 3; i++) {
    var myLabel = this.Controls["label" + i.ToString()] as Label;
    //Do stuff with myLabel
}
Related