Change all background buttons except button click

I am working on a form that has many buttons. When the user clicks one button, the background should change color. If they click on another button on the form, its background should change color, and the previous button colors should revert to their original color.

I can do this by hardcoding in each button, but there are many buttons in this form. I'm sure there must be a more efficient way to do this.

I still have it

foreach (Control c in this.Controls)
{
    if (c is Button)
    {
        if (c.Text.Equals("Button 2"))
         {
             Btn2.BackColor = Color.GreenYellow;
         }
         else
         {

         }
    }
}

      

I can get the background for Btn2 to change. How to change the background for all other buttons in the form. Any ideas how I could do this without having to hardcoding each button.

+3


source to share


2 answers


The code below will work regardless of the number of buttons in the form. Just set the method button_Click

as an event handler for all buttons. When you click on the button, its background will change color. When you click on any other button, this button background will change color and the previously button background color will revert to the default background color.

// Stores the previously-colored button, if any
private Button lastButton = null;

      



...

// The event handler for all button who should have color-changing functionality
private void button_Click(object sender, EventArgs e)
{
    // Change the background color of the button that was clicked
    Button current = (Button)sender;
    current.BackColor = Color.GreenYellow;

    // Revert the background color of the previously-colored button, if any
    if (lastButton != null)
        lastButton.BackColor = SystemColors.Control;

    // Update the previously-colored button
    lastButton = current;
}

      

+4


source


This will work as long as you don't have control containers (like panels)



foreach (Control c in this.Controls)
{
   Button btn = c as Button;
   if (btn != null) // if c is another type, btn will be null
   {
       if (btn.Text.Equals("Button 2"))
       {
           btn.BackColor = Color.GreenYellow;
       }
       else
       { 
           btn.BackColor = Color.PreviousColor;
       }
   }
}

      

0


source







All Articles