I would appreciate help for changing the color of a button, to the color of a different button that was just pressed. I have two arrays of buttons defined by:
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
Button[,] btn2 = new Button[10, 20];
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.Empty;
}
}
for (int v = 0; v < btn2.GetLength(0); v )
{
for (int w = 0; w < btn2.GetLength(1); w )
{
btn2[v, w] = new Button();
btn2[v, w].SetBounds(40 * v, 40 * w, 40, 40);
btn2[v, w].Click = new EventHandler(this.btn2Event_click);
Controls.Add(btn2[v, w]);
btn2[v, w].BackColor = Color.Empty;
}
}
I can change the color of any button within btn2 (after selecting a button from btn) using below:
void btnEvent_click(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.FromName(buttonColor.colorResult);
}
void btn2Event_click(object sender, EventArgs e)
{
string selectedColor = "";
selectedColor = btn2[0,0].BackColor.ToString();
int pFrom = selectedColor.IndexOf("[") "[".Length;
int pTo = selectedColor.LastIndexOf("]");
buttonColor.colorResult = selectedColor.Substring(pFrom, pTo - pFrom);
}
But as you can see it is only btn2[0,0]. I am looking for a way to make this work for whichever button I press within btn2.
CodePudding user response:
in an event in a control, sender is usually the exact control you just interacted with. In your case there is no sign that i wouldn't always be the button you literally just clicked. All you need to do then is to cast the object back to the type you know it will be. So without any exception checks here's an example of what would work
void btn2Event_click(object sender, EventArgs e)
{
// get the sender as a button
Button button = ((Button)sender);
string selectedColor = button.BackColor.ToString();
int pFrom = selectedColor.IndexOf("[") "[".Length;
int pTo = selectedColor.LastIndexOf("]");
buttonColor.colorResult = selectedColor.Substring(pFrom, pTo - pFrom);
}
