简单表单,如何迭代其中的所有按钮(Visual Sudito 2010 + C#)

本文关键字:按钮 Visual 2010 Sudito 表单 何迭代 简单 迭代 | 更新日期: 2023-09-27 17:56:12

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

简单表单,如何迭代其中的所有按钮(Visual Sudito 2010 + C#)

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

buttons.Select((btn,index)=>{
            if(index%2==0)btn.BackgroundColor=Color.Red
            else
                 btn.BackgroundColor=Color.White;
       });
您可以使用

以下代码:

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