How to Do Something on All Controls in WinForms

One of the questions, I got in my mailbag is a question on how to implement some blurb of code on multiple controls. For instance, I have several buttons. I want all the buttons to have the same behavior but don’t want to code each button. So how to do something in multiple controls in WinForms But those are my words, lets hear the actual issue.

“I have several textboxes that I want to validate that text is in them. If it is not then I want them to turn red. There are like 15 fields and I don’t want to take them one at a time. Is there a way to assign all buttons a function to check if values are missing?”

Kalid

Button Controls Doing Something

I have an example using buttons and their background colors. Lets take a look at the controls.

GUI of Application

Here we have an app that contains three buttons. We also have three check boxes. Each with their default names. We are using the check boxes to act as a control that not all click events are modified. The star of this show is the buttons. When you click them, I want them to turn red and when you click them again, I want them to turn back to a control color.

After button clicks

So how did I do this? Lets dig into it.

using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace ExtraMethodsOnControls
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeButtons();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            
        }
 
        private void InitializeButtons()
        {
            foreach(Control control in this.Controls)
            {
                if(control is Button)
                {
                    control.Click += changeBackgroundColor;
                }
 
            }
        }
 
        public void changeBackgroundColor(object sender, EventArgs e)
        {
            Button btn = sender as Button;
 
            if (btn.BackColor == SystemColors.Control)
            {
                btn.BackColor = Color.Red;
            }
            else if (btn.BackColor == Color.Red)
            {
                btn.BackColor = SystemColors.Control;
            }
            else
            {
                btn.BackColor = Color.Yellow;
            }
  
        }
    }
}

So first, we are going to start at the bottom. I think it will make more sense if we start there. Here I have a function, changeBackgroundColor. It takes the sender object and casts it as a button. Then it checks that button’s background property to see if it is the control color. If it is then it turns it red. Should it not be that color then it checks to see if it is red. If it is then switch back to control color. Finally, if both conditions fails we get a yellow button. That should never happen.

Next up we have the InitializeButtons function. In here we search through all the controls for the buttons. When we find one we add our changeBackgroundColor function to its click event’s delegates.

After that we have an empty click event for button1. This is just to show that the click even is indeed empty.

Finally we have the Form1 constructor. This has the normal InitializeComponents call but also a call to our InitializeButtons. Here the function that kicks off the assignment process.

Let’s make the something into validation check and the buttons into text boxes controls in WinForms.

So we have a pattern to follow with our buttons, lets expand it out to the textboxes. Since we are doing validation, it would make sense to have it do the action upon leaving the textbox. So that is where we will attach the service. To expand the example lets add 3 textboxes and keep there default names.

With that interface out of the way, lets dig into the code.

using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace ExtraMethodsOnControls
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeControls();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            
        }
 
        private void InitializeControls()
        {
            foreach(Control control in this.Controls)
            {
                if(control is Button)
                {
                    control.Click += changeBackgroundColor;
                }
                else if(control is TextBox)
                {
                    control.Leave += validateTextBoxHaveValue;
                }
 
            }
        }
 
        public void changeBackgroundColor(object sender, EventArgs e)
        {
            Button btn = sender as Button;
 
            if (btn.BackColor == SystemColors.Control)
            {
                btn.BackColor = Color.Red;
            }
            else if (btn.BackColor == Color.Red)
            {
                btn.BackColor = SystemColors.Control;
            }
            else
            {
                btn.BackColor = Color.Yellow;
            }
  
        }
 
        public void validateTextBoxHaveValue(object sender, EventArgs e)
        {
            TextBox txt = sender as TextBox;
 
            if(txt.Text.Trim().Length == 0)
            {
                txt.BackColor = Color.Red;
            }
            else
            {
                txt.BackColor = SystemColors.Window;
            }
        }
    }
}

Once again, lets start at the bottom.

First we have the validateTextBoxHaveValue function.

Here we cast the sender object from the parameter into a TextBox. We then check that textbox’s text value for a non 0 number of characters. Here I trimmed it to prevent a space from counting. If it is empty then change to color red. If a value is present then switch it back to its window color.

Above that is the changeBackgroundColor for our buttons. It was left alone so I will skip it here since it is not doing anything for this example.

I renamed the InitializeButton to InitializeControls since that is what it is doing. I added a check for the presence of Textboxes and if found add a validateTextBoxHaveValue delegate.

Like before, the click event for button 1 is empty. Finally the Form1 constructor is the same except for the different name of the InitializeControls function.

Now the app will open. All textboxes will be white. If I enter and leave they will turn red. If I add text they will turn back to white.

Start Up GUI
At Startup
Code something once but applied validation to all WinForms textbox controls.
Went into each textbox causing the leave function to fire.
Fixed the two red by putting text into it.
Went back and added text turning the textboxes back to white

Hopefully that is a quality walk through on the question of how to make something happen to all controls in WinForms. I will warn you that if you have controls with controls in them. You will need to handle that in that in the InitializeControls function by doing the same loop only for the individual control.

If you like tutorials like this then leave a comment down below.

Leave a Reply

Your email address will not be published. Required fields are marked *