我正在尝试将所有标签的背景颜色设为黑色,但如果我这样做,它将如下所示:
lable0.BackColor = Color.Black;
lable1.BackColor = Color.Black;
再多108次。所以我想知道是否有办法使用foreach循环:
int[] labels = new int[] {1, 2, 3...110};
foreach (int i in labels)
{
label.BackColor = Color.Black;
}
答案 0 :(得分:6)
如果您的标签是您表单的直接子项(我认为这是winforms),这对您有用:
foreach(Label lbl in this.Controls.OfType<Label>())
{
lbl.BackColor = Color.Black;
}
答案 1 :(得分:0)
Winforms控件是分层的,因此您需要递归地遍历它们以查找所有标签:
public static IEnumerable<Control> WalkControls(this Control topControl)
{
if (topControl == null)
yield break;
yield return topControl;
foreach (var child in topControl.Controls.OfType<Control>())
foreach (var subChild in WalkControls(child))
yield return subChild;
}
public static void SetControlTreeBackColor<TControl>(Control topControl, Color color) where TControl : Control
{
foreach (var childControl in topControl.WalkControls().OfType<TControl>())
childControl.BackColor = color;
}
在这里你会使用&#34;标签&#34; for&#34; TControl&#34;。