循环遍历具有相似名称的标签 C#

Looping through labels with similar name C#

我想根据文本文件中的内容更改某些标签的背景:

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();
        }

有超过 50 个名为 "lbl101"、"lbl102"、"...."、"lbl150"

的标签

试一试:

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
    }
} 

您可以在 Controls 形式的集合上使用 OfType<T>() 方法遍历它们,例如:

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

这仅适用于作为表单直接子项的标签,嵌套在其他用户控件或嵌套面板中的标签不会受到影响,因为 you have to do it recursively

遍历表单的 Controls 集合以检查 Label 对象。然后,根据指定的值进行相应的修改。

1.) 创建一个包含所有标签的列表。

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

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

2.) 如果你的words[]字符串是你可以写的颜色名称:

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

有有效的解决方案:

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();
        }