I am trying to make a array of 8x8 buttons, and so far it works. Now I have stumbled upon a problem. I want the color of the button (backcolor) to change when it is clicked. And change to a different color when clicked again.
This is my code so far:
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8,8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x,y] = new Button();
btn[x,y].SetBounds(40 * x, 40 * y, 40, 40);
btn[x,y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x,y].BackColor = Color.Black;
}
}
/*
btn.Click += new EventHandler(this.btnEvent_click);
btn[x,y].Text = Convert.ToString(x+","+y);
Controls.Add(btn);
btn[x,y].Click += new EventHandler(this.btnEvent_click);
*/
}
private void form1_load(object sender, EventArgs e)
{
}
void btnEvent_click(object sender, EventArgs e)
{
(Control)sender).BackColor = Color.Red;
}
}
}
So far I can only change the color to red, and I've tried multiple if and for statements to change the color a second time.
Could anyone help me out?
Hi Temporary you can use below solution:
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Yellow;
break;
case "Black":
ctrl.BackColor = Color.White;
break;
case "White":
ctrl.BackColor = Color.Red;
break;
case "Yellow":
ctrl.BackColor = Color.Purple;
break;
default:
ctrl.BackColor = Color.Red;
break;
}
}
I know there can be a better solution also, but meanwhile you can go with this...you can add more colors also in switch statment as required
You can make a new class, tha inherit from Button and handle internally the color change, something like this:
class TwoColorButton : Button
{
private int stateCounter = 0;
private Color[] states = new Color[] { Color.Black, Color.Red };
public TwoColorButton()
: base()
{
this.BackColor = states[stateCounter];
this.Click += this.clickHandler;
}
protected void clickHandler(object sender, EventArgs e)
{
stateCounter = stateCounter == 0 ? 1 : 0;
this.BackColor = states[stateCounter];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With