Click here to Skip to main content
15,849,615 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how can i write a loop to change the multiple button's background color in a single click event.
lets say i have 20 buttons in my program , if i click on one button it should change the background color of all 20 buttons . i dont want to write 20 lines. i did try this in a loop with Button(i) but the getting error "Button is class type and cannot be used as an expression" i am using visual studio 2019. any suggestion!!!!!

What I have tried:

loop with Button(i) as well as btn as string="Button" & (i)
Posted
Updated 25-Feb-20 20:17pm

1 solution

You can put the 20 buttons in a list.
On click: iterate the list and change the colour.
C#
public class TheForm : Form
{
   private List<Button> _theList = new List<Button>();

   public TheForm()
   {
      InitializeComponent();
      PopulateList();
   }

   private void PopulateList()
   {
      _theList.AddRange(new Button[] {
         button01, button02, button03, button04, button05,
         button06, button07, button08, button09, button10,
         button11, button12, button13, button14, button15,
         button16, button17, button18, button19, button20
      });
   }

   private void TheButton_Click(object sender, EventArgs e)
   {
      foreach (Button button in _theList)
      {
         button.BackColor = /* the colour */;
      }
   }
}
button01 to button20 are the Names of button instances on your form.
 
Share this answer
 
Comments
m-sk43 27-Feb-20 11:23am    
Thanks Phil, much appreciated

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900