简体   繁体   中英

how to set backcolor for all textboxes in winform globally C#?

how to set back color for all text boxes in win form globally? can we set it somewhere like in a global variable and use when needed? I need to set the back color of control in form_load from a global variable instead of writing

mytextbox1.BackColor = Color.Red;
mytextbox2.BackColor = Color.Red; 
 private void SetRedColorToTextBoxes()
 {
     Action<Control.ControlCollection> func = null;

     func = (controls) =>
         {
             foreach (Control control in controls)
                 if (control is TextBox)
                     (control as TextBox).BackColor = Color.Red;
                 else
                     func(control.Controls);
         };

     func(Controls);
 }

and call SetRedColorToTextBoxes() function in form load.

    private void YourForm_Load(object sender, EventArgs e)
    {
        SetRedColorToTextBoxes();
    }

Edit Add a .cs file and put the code there.

  class Helper
   {
    public void SetRedColorToTextBoxes(Form frm)
    {
        Action<Control.ControlCollection> func = null;

        func = (controls) =>
        {
            foreach (Control control in controls)
                if (control is TextBox)
                    (control as TextBox).BackColor = Color.Red;
                else
                    func(control.Controls);
        };

        func(frm.Controls);
    }
}

and call it your form load as :

 private void YourForm_Load(object sender, EventArgs e)
    {
        // this means instance of  currentform.
       (new Helper()).SetRedColorToTextBoxes(this);
    }

Can i make sure you are not looking for themes. Some third parties like devexpress gives option to design your own themes

作为对上述Arshad解决方案的略微更改,我还将使该方法能够实时进行着色:

public void SetRedColorToTextBoxes(Form frm, Color myColor)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM