Crej00
Crej00

Reputation: 17

Change Button Colors with a click

im starting to code with c# and i have a problem. Basically, i want to jump colors clockwise. For example, if i click the orange button the gold button turns white and the second button turns gold. I want to do that for all buttons until the button bellow gold button be gold and the others stay white (clockwise)

You can see what i explained above in this image.

The only code that i have for now is:

if (button9.Enabled)
{
    button2.BackColor = Color.Gold;
    button1.BackColor = Color.White;
}

Button 9 is the jump button.

If you could help me i would be very grateful.

Upvotes: 0

Views: 310

Answers (1)

cg-zhou
cg-zhou

Reputation: 563

Here is an simple WinForm example

You can follow the serial number (1.1 ~ 4.2) in the code comment to get the code idea :)

using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // 2.1 initialize a list, and add all buttons into it.
            this.Buttons.Add(button2);
            this.Buttons.Add(button3);
            this.Buttons.Add(button4);

            // 2.2. initialize high light index.
            HighlightIndex = 0;

            // 2.3. refresh all buttons' color.
            RefreshColor();
        }

        // 1.1 we use this List to store all buttons.
        private List<Button> Buttons = new List<Button>();

        // 1.2 indicated the index of the highlighted button
        private int HighlightIndex = 0;

        private void button1_Click(object sender, System.EventArgs e)
        {
            // 4.1 when user click the jump button, increme the highlight index.
            HighlightIndex = HighlightIndex + 1;
            if (HighlightIndex >= Buttons.Count)
            {
                HighlightIndex = 0;
            }

            // 4.2 refresh all buttons' color.
            RefreshColor();
        }

        private void RefreshColor()
        {
            // 3.1 loop all buttons by index.
            for (int i = 0; i < Buttons.Count; i++)
            {
                if (i == HighlightIndex)
                {
                    // 3.2 if the index equals the highlight button index, update BackColor as Gold.
                    Buttons[i].BackColor = Color.Gold;
                }
                else
                {
                    // 3.3 set normal button BackColor as White.
                    Buttons[i].BackColor = Color.White;
                }
            }
        }
    }
}

Upvotes: 1

Related Questions