Reputation: 9866
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.
Upvotes: 0
Views: 1560
Reputation: 1219
You can use following code:
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;
}
}
Upvotes: 2
Reputation: 20575
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;
}
}
Upvotes: 0
Reputation: 10995
Is it an array or list of buttons? Then you could do:
buttons.Select((btn,index)=>{
if(index%2==0)btn.BackgroundColor=Color.Red
else
btn.BackgroundColor=Color.White;
});
Upvotes: 2