You can select all controls of a particular type by using the System.Linq
extension method, OfType
, and if you iterate over them in a loop, you can set all their BackColor
properties:
private void button1_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
{
foreach (var panel in Controls.OfType<Panel>())
{
panel.BackColor = cd.Color;
}
}
}
Note that this only iterates over the controls belonging directly to the form itself. If any of the panels are inside a container control, then we will need to look through each control to see if it contains any panels.
We can write a helper method for this that takes in a Control
to inspect, a Color
to use for the BackColor
, and a Type
that specifies the type of control we want to set the back color for.
Then we first check if the Control
is the same type as the one we're looking for, and if it is, set it's backcolor. After that, we loop through all it's children and recursively call the method again on them. This way, if we pass the parent form as the Control
, we will iterate through all the controls:
private void SetBackColorIncludingChildren(Control parent, Color backColor, Type controlType)
{
if (parent.GetType() == controlType)
{
parent.BackColor = backColor;
}
foreach(Control child in parent.Controls)
{
SetBackColorIncludingChildren(child, backColor, controlType);
}
}
private void button1_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
{
// Pass 'this' to the method, which represents this 'Form' control
SetBackColorIncludingChildren(this, cd.Color, typeof(Panel));
}
}