首页 > 解决方案 > 如何在 C# 中单击按钮时更改按钮颜色?

问题描述

我正在创建一个在线测试应用程序,其中我在运行时在表单加载时生成大约 100 个按钮。这是一段代码:

private void addQuestion_Reviewbutton()
        {
            for (int i = 1; i <= clsGlobalVars.gnTotalQuestion; i++)
            {
                Button button = new Button();
                button.Location = new Point(160, 30 * i + 10);
                button.Click += new EventHandler(ButtonClickOneEvent);                
                button.Tag = i;                
                button.Name = "Question" + i;
                button.Text = i.ToString();
                button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button));
                button.BackgroundImageLayout = ImageLayout.Stretch;//.Zoom;
                button.FlatAppearance.BorderSize = 0;
                button.Size = new System.Drawing.Size(47, 41);
                button.BackColor = Color.Transparent;
                button.FlatStyle = FlatStyle.Flat;
                button.Font = new System.Drawing.Font("Segoe UI Semibold", 12);
                button.ForeColor = Color.White;
                button.Cursor = Cursors.Hand;
                flowLayoutPanel1.Controls.Add(button);
                
            }
        }

并单击此按钮,我正在更改背景颜色。

void ButtonClickOneEvent(object sender, EventArgs e)
        {
            Button button = sender as Button;
            //button.BackColor = Color.Yellow;
            button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button_Orange));
            lblQuestionNo.Text = ((int)button.Tag).ToString()+".";
            btnNext.Focus();
            
        }

我在名为“下一步”的表单上有一个按钮。现在我的问题是,如果我目前的问题是“1”。然后我按下按钮下一步我想更改文本为“2”的按钮的背景图像。

我需要您的宝贵指导来解决这个问题。

标签: c#webforms

解决方案


哟检查这个!

tldr; 指导是

  1. 点击事件是否转到 ButtonClickOneEvent ?

  2. 如何调用其他按钮

  3. ...

  4. 利润?

      protected void Page_Load(object sender, EventArgs e)
     {
        addQuestion_Reviewbutton();
     }
    
      void ButtonClickOneEvent(object sender, EventArgs e)
     {
         Button button = sender as Button;
    
         var currentbtn_id = button.ID; 
         int nextid =  Convert.ToInt32( currentbtn_id.Substring("Question".Length)) + 1;
        var nextBtn = flowLayoutPanel1.FindControl("Question"+ nextid.ToString() );
         (nextBtn as Button).BackColor = Color.Red;
    
     }
    

在此处输入图像描述


推荐阅读