Looping through labels with similar name C#

…衆ロ難τιáo~ 提交于 2019-12-14 03:19:32

问题


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


来源:https://stackoverflow.com/questions/36203068/looping-through-labels-with-similar-name-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!