Looping through labels with similar name C#

2019-09-12 05:50发布

问题:

I want to change the background of some labels depending on what is written on a text file:

private void Form3_Load(object sender, EventArgs e)
        {
            string[] words = new string[7];
            StreamReader read = new StreamReader(path);
            while(!read.EndOfStream)
            {
                string line = read.ReadLine();
                words = line.Split(';');
                if(words[6] == "no") 
                {
                    //-----What I have to write here---
                }              
            }
            read.Close();
        }

There are over 50 labels named "lbl101","lbl102","....","lbl150"

回答1:

try it:

if(words[6] == "no") 
{
    int count = 150;
    for (int a = 1 ; a < count; a++)
    {
        Label currentLabel = (Label)this.Controls.Find("lbl"+a,true)[0];    
        //change color of currentLabel
    }
} 


回答2:

There's the working solution:

private void Form3_Load(object sender, EventArgs e)
        {
            int count = 101;
            string[] words = new string[7];
            StreamReader read = new StreamReader(pathRooms);
            while(!read.EndOfStream)
            {
                string line = read.ReadLine();
                words = line.Split(';');
                if (words[6] == "no")
                {

                        Label currentLabel = (Label)this.Controls.Find("lbl" + count, true)[0];
                        currentLabel.BackColor = Color.Yellow;

                }
                count = count + 1;
            }
            read.Close();
        }


回答3:

You can iterate all over them using OfType<T>() method on Controls collection of form like:

if(words[6] == "no") 
{
    foreach(var label in this.Controls.OfType<Label>().Where(x=>x.Name.Contains("lbl")))
    {
         label.Text = "Some Text";
    }
}

This will only work on the labels that are direct child of form, labels nested inside other user controls or nested panels will not be affected, for that you have to do it recursively.



回答4:

Loop through the Controls collection of the form checking for Label objects. Then, amend accordingly as per the specified value.



回答5:

1.) Create a List with all the labels.

Label lbl101 = new Label();
Label lbl102 = new Label();
...

List<Label> labels = new List<Label>()
{
    lbl101,
    lbl102
...
};

2.) If your words[] string is the name of the color you can write:

if(words[6] == "no") 
{
   System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml(words[..]);
   foreach(Label l in Labels)
   {
       l.BackColor = myColor;
   }
}  


标签: c# forms labels