0

For now I have created a Windows Forms Project with a single form and six buttons added. What I want to do right now is find out how I can iterate through all my buttons and the goal is to set the background color of every button with an even number a different color. Like - button1 - white, button2-red, button3-white, button4-red and so on. Right know I don't know either how to iterate the buttons or change the background color property but the questions is about iterating so I'd appreciate help about this topic if someone knows how to change the background color of the button it will save me time and maybe new question here.

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 に答える