0

I have created a class named Design

contain this codes

public static void Edit(Form frm, Color bkColor, Color btnColor,Color pnlColor)
{
    frm.BackColor = bkColor;
    frm.RightToLeft = RightToLeft.Yes;
    frm.RightToLeftLayout = true;
    foreach (Button btn in frm.Controls.OfType<Button>())
    {
        btn.BackColor = btnColor;
    }
    foreach (Panel pnl in frm.Controls.OfType<Panel>())
    {
        pnl.BackColor = pnlColor;
    }
}

and I am calling it by this in the form:

Design.Edit(this, Color.Blue, Color.Green, Color.Yellow);

NOW it works good on the form background BUT on the panel and buttons not working at all

Rand Random
  • 7,300
  • 10
  • 40
  • 88
GMCadiom
  • 23
  • 1
  • 7
  • Controls are organized in a tree structure, always best visited with a recursive method. Googling "windows forms recursively visit all controls" provides you with good hits. – Hans Passant Feb 27 '19 at 16:31
  • `BackColor` is an ambient property. You don't need to change `BackColor` of all controls, changing back color of the form would be enough. Same for `RightToLeft` property. – Reza Aghaei Feb 27 '19 at 16:40

1 Answers1

0

You need a recoursive search of your control inside of all the controls of the form. Look that accepted answer that implement a very good recoursive approach.

Doing this:

frm.Controls.OfType<Button>()

you search only in the first layer of controls of your forms, so if you've a button inside a panel or another element (the 99,999999% of the situations) your foreach cannot find it.

adapting the Accepted answer at your Question:

public IEnumerable<Control> GetAll(this Control control,Type type)
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => ctrl.GetAll(type))
                              .Concat(controls)
                              .Where(c => c.GetType() == type);
}

[...]

foreach (Button btn in frm.GetAll(typeof(Button)))
    {
        btn.BackColor = btnColor;
    }

L-

Legion
  • 760
  • 6
  • 23