如何清除按钮颜色第二次点击流程布局面板c#

问题描述 投票:0回答:2

我在流程布局面板中有很多按钮。我以编程方式创建了这些按钮。但是我没有点击按钮,它的颜色会在第二次点击后变为浅绿色将重置颜色。我为流布局面板编写了这个处理程序。如何进行第二次点击将清除按钮颜色:

   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;

        }
c# button eventhandler flowlayoutpanel
2个回答
1
投票

那么将简单的if条件添加到这样的按钮处理程序中呢?

    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;
        }
    }

1
投票

改变你的ButtonClickHandler

public void ButtonClickHandler(Object sender, EventArgs e)
        {
            var currentButton = ((Button)sender);
            if(currentButton != null)
            {
               currentButton.BackColor = currentButton.BackColor == Color.LightGreen ? Color.LightGray : Color.LightGreen;
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.