简体   繁体   中英

How to change button color on button click in C#?

I am creating an online test application, in which I am generating approximately 100 buttons at run time on form load. Here is the piece of code:

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

and on this button click, I am changing the background-color.

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

I have a button on the form Named "Next". Now my problem is that if I am currently in question "1." and I press the button next I want to change the background image of the button whose text is "2".

I need your valuable guidance to solve this problem.

Yo check this !

tldr; the guidance are

  1. Is the click event go to ButtonClickOneEvent?

  2. How to call other button

  3. ...

  4. profit?

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM