0

现在我已经创建了一个Windows Forms Project带有一个表单并buttons添加了六个的表单。我现在要做的是找出如何遍历所有按钮,目标是将每个带有偶数的按钮的背景颜色设置为不同的颜色。比如 - button1 - white, button2-red, button3-white,button4-red等等。是的,我不知道如何迭代按钮或更改background color属性,但问题是关于迭代的,所以如果有人知道如何更改按钮的,我将不胜感激有关此主题的帮助,background color这将节省我的时间,也许是新的问题在这里。

4

3 回答 3

2

您可以使用以下代码:

foreach(Control c in this.Controls) // this is the form object on which Controls is the ControlCollection
{
   if(c is Button)
   {
       KnownColor[] names = (KnownColor[]) Enum.GetValues(typeof(KnownColor));
       KnownColor color= names[randomGen.Next(names.Length)];
       Color color = Color.FromKnownColor(randomColorName);
       c.BackColor = color;
   }
}
于 2013-01-26T13:07:58.907 回答
2

它是按钮数组还是按钮列表?然后你可以这样做:

buttons.Select((btn,index)=>{
            if(index%2==0)btn.BackgroundColor=Color.Red
            else
                 btn.BackgroundColor=Color.White;
       });
于 2013-01-26T13:08:56.720 回答
0
        foreach (Control control in Controls)
        {
            Button button = control as Button;
            if (button == null) continue;
            switch (button.Name)
            {
                case "button1":
                    button.BackColor = Color.Red;
                    break;
                case "button2":
                    button.BackColor = Color.Yellow;
                    break;
                case "button3":
                    button.BackColor = Color.Green;
                    break;
                default:
                    button.BackColor = Color.Black;
                    break;

            }
        }
于 2013-01-26T13:10:02.950 回答