循环遍历C#中的标签

时间:2016-03-24 13:04:32

标签: c# forms winforms label

我有九个名称为"lbl101""lbl102",...

的标签

我想这样做:

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

我该怎么做?

6 个答案:

答案 0 :(得分:9)

您可以将控件添加到集合中,然后循环播放。

var labels = new List<Label> { lbl101, lbl102, lbl103 };

foreach (var label in labels)  
{  
    label.BackColor = Color.Red;  
}

或者,如果您只想在Label上以“lbl10”开头的每个Form,您可以使用LINQ查询控件集合:

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

答案 1 :(得分:4)

如果在表单上设置了标签,则可以使用 Linq

  var labels = Controls // or MyPanel.Controls etc. if labels are on panel
    .OfType<Label>()
    .Where(label => label.Name.StartsWith("lbl10"));

  foreach (var label in labels)   
    label.BackColor = Color.Red;  

答案 2 :(得分:1)

循环通过他们所在的容器并获取对它们的引用。

for(int i = 0; i<9; i++)  
{  
   var label = (Label)yourForm.FindControl("lbl10" + i.ToString());  
   label.BackColor = Color.Red;  
}

答案 3 :(得分:0)

最简单的事情可能是将它们全部列出来:

lbl100.BackColor = Color.Red;
lbl101.BackColor = Color.Red;
lbl102.BackColor = Color.Red;
lbl103.BackColor = Color.Red;
lbl104.BackColor = Color.Red;
lbl105.BackColor = Color.Red;
lbl106.BackColor = Color.Red;
lbl107.BackColor = Color.Red;
lbl108.BackColor = Color.Red;

这是最简单的方法。如果你真的想要花哨,你可以将它们全部放在一个数组中并迭代它:

Label[] labels = new Label[]{
    lbl100, lbl101, lbl102, lbl103, lbl104, lbl105, lbl106, lbl107, lbl108
};
for (int i = 0; i < labels.Length; i++)
{
    labels[i].BackColor = Color.Red;
}

或者,如果您知道所有标签都是某个控件的子项,并且该控件中没有其他标签,则可以执行此操作:

foreach (Control c in someControl.Controls)
{
    if (c is Label)
    {
        ((Label)c).BackColor = Color.Red;
    }
}

答案 4 :(得分:0)

 public void changebackground()
 {           
     Label mylabel;

     foreach (Control con in this.Controls) 
     {
         if (con.GetType() == typeof (Label)) //or any other logic
         {
             mylabel = (Label)con;
             mylabel.BackColor = Color.Red;
         }
     }
 }

答案 5 :(得分:0)

在Windows Form中,要指向一个控件,直接用下面的语句调用即可

this.Controls[control name]

例如

this.Controls["label1"].BackColor = Color.Blue;

所以你的问题的答案

for (int i = 0; i < 9; i++)
{  
  this.Controls["lbl10" + i.ToString()].BackColor = Color.Red;
}