Search code examples
c#formswinformslabel

Looping through labels in C#


I have nine labels with the names "lbl101", "lbl102", ...

I want to do this:

for (int i = 0; i < 9; i++)
{
    sting name = "lbl10" + i;
    name.BackColor = Color.Red;
}

How can I do this?


Solution

  • You can add the controls to a collection, and loop through that.

    var labels = new List<Label> { lbl101, lbl102, lbl103 };
    
    foreach (var label in labels)  
    {  
        label.BackColor = Color.Red;  
    }
    

    Alternatively, if you just want every Label on the Form that starts with "lbl10", you can use LINQ to query the collection of controls:

    var labels = this.Controls.OfType<Label>()
                              .Where(c => c.Name.StartsWith("lbl10"))
                              .ToList();