Search code examples
c#buttoneventhandlerflowlayoutpanel

how to clear button color second click in flow layout panel c#


I have a lot of buttons in flow layout panel. I created these buttons programmatically. But I didn't if click button its color will be light green after second click will be reset color. I wrote this handler for flow layout panel. How can I do second click will clear button color:

   private void Form1_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append( "3 x coca cola 33 cl");
            sb.Append(Environment.NewLine);
            sb.Append("DIN");
            sb.Append("\t\t");
            sb.Append("200");    
            //button2.Text = sb.ToString();

            string products = "30000|3;3110002;Cola;400;150;100;1;1000|3;3110003;Snickers;400;150;100;1;1000|3;3110004;NesttleCrunch;400;150;100;1;1000|3;3110005;Marlbora;400;150;100;1;1000|3;3110006;Orange;400;150;100;1;1000|3;3110007;Milk;400;150;100;1;1000|3;3110008;Water;400;150;100;1;1000|3;3110009;Banana;400;150;100;1;1000|3;3110010;Honey;400;150;100;1;1000|3;3110011;Beer;400;150;100;1;1000|3;3110012;Hazelnut;400;150;100;1;1000|3;3110013;RedBull;400;150;100;1;1000|3;3110014;ChewingGum;400;150;100;1;1000|3;3110015;Apple;400;150;100;1;1000";


            string[] listproducts = products.Split('|');

            lblAvaliablePoint.Text = listproducts[0];

            for (int i = 1; i < listproducts.Count();i++ )
            {

                string[] perproduct = listproducts[i].Split(';');

                    Button newButton = new Button();
                    newButton.Size = new System.Drawing.Size(170, 87);
                    newButton.BackColor = Color.LightGray;
                    newButton.UseVisualStyleBackColor = false;
                    newButton.Tag =perproduct[1];
                    newButton.Text = perproduct[0] + "x" + perproduct[2];
                    newButton.Click += new EventHandler(ButtonClickHandler);

                    flowLayoutPanel1.Controls.Add(newButton);

            }
                flowLayoutPanel1.VerticalScroll.Maximum = flowLayoutPanel1.Height+40;
            flowLayoutPanel1.VerticalScroll.LargeChange = 30;

        }

   public void ButtonClickHandler(Object sender,EventArgs e)
        {

                ((Button)sender).BackColor = Color.LightGreen;

        }

Solution

  • What about add simple if condition into button handler like this?

        public void ButtonClickHandler(object sender, EventArgs e)
        {
            if (((Button)sender).BackColor == Color.LightGreen)
            {
                ((Button)sender).BackColor = Color.White; // Your default color
            }
            else
            {
                ((Button)sender).BackColor = Color.LightGreen;
            }
        }