Reputation: 37
Ok i have a 100 buttons in a square. As well as other functional buttons outside (quit/clear/fill buttons etc). The clear button will turn all buttons on the forms backcolor to lightgray, and the fill button will turn all buttons on the forms backcolor to lightblue.
private void btnClear_Click(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
if (ctrl is Button && ctrl.BackColor == Color.LightBlue)
ctrl.BackColor = Color.LightGray;
}
private void btnFill_Click(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
if (ctrl is Button && ctrl.BackColor == Color.LightGray)
ctrl.BackColor = Color.LightBlue;
}
I's looking to make the clear and fill buttons only work on the 100 buttons in a square and not the other buttons. Can I use a panel/group box? or make a collection of buttons? reference only those buttons somehow? I'm obviously new so any advice and especially code would be very helpful :)
Upvotes: 1
Views: 68
Reputation: 66439
Since they're already in a large square, it should be easy to move them all into a Panel as you suggested, then only change controls inside the Panel instead of the entire Form.
You can remove the ctrl is Button
check, since the only controls in the panel are buttons.
Also, you don't need to check the current BackColor of the button before changing it, unless you've got something going on in the BackColorChanged
event that you're trying to avoid running.
private void btnClear_Click(object sender, EventArgs e)
{
foreach (var ctrl in pnlButtons)
ctrl.BackColor = Color.LightGray;
}
private void btnFill_Click(object sender, EventArgs e)
{
foreach (Control ctrl in pnlButtons)
ctrl.BackColor = Color.LightBlue;
}
Alternatively, you could store the buttons you want to change in a list. This should be easy if you're already generating the buttons at runtime.
var myButtons = new List<Button>();
myButtons.Add(someButton); // add buttons
foreach(var btn in myButtons)
btn.BackColor = Color.LightBlue;
Upvotes: 1
Reputation: 103437
Yes, you can use a Panel or Group Box.
For example, you could put the buttons into a panel, then you can modify your code to refer to panel1.Controls
instead of this.Controls
.
Upvotes: 0