Reputation: 83
OK let's say we have buttons arranged in the following form 5x5
[11] [12] [13] [14] [15]
[21] [22] [23] [24] [25]
[31] [32] [33] [34] [35]
[41] [42] [43] [44] [45]
[51] [52] [53] [54] [55]
And want for example, if I click on button 34, to change the color of the button 24, 44, 33 and 35. The problem is I do not know how to do that when I click on a button to return any of these values. Take a pseudocode of what I want to do.
When I press the button [i, j]:
Change color of button[i-1, j];
Change color of button[i +1, j];
Change color of button[i, j +1];
Change color of button[i, j-1];
So when I press a button, I need to somehow get the values i, j of the button and I may handle other buttons on the same style (i +1, j, etc.)
I could treat separately each button.....
private void button1_Click(object sender, EventArgs e)
{ // change colors
}
private void button2_Click(object sender, EventArgs e)
{ // change colors
}
private void button3_Click(object sender, EventArgs e)
{ // change colors
}
....
private void button25_Click(object sender, EventArgs e)
{ // change colors
}
, .....but I have 25 buttons and I don't want to write the same code in all 25 keys.
What I want is that :
private void button[i][j]_Click(object sender, EventArgs e)
{
button[i+1][j].BackColor = Color.Red;
button[i][j+1].BackColor ...... etc. etc.
// I know is incorrect, but is just how I want to act, if you understand me.
}
Excuse my bad English.
Upvotes: 0
Views: 389
Reputation: 13033
I think the most elegant solution is to use TableLayoutPanel
to arrange all the buttons. Then you can handle all the buttons this way:
private void button_Click(object sender, EventArgs e)
{
Button clickedBtn = sender as Button;
var cp = tableLayoutPanel1.GetCellPosition(clickedBtn);
Button up = (Button)tableLayoutPanel1.GetControlFromPosition(cp.Column, cp.Row - 1);
//up.Color = ...
Button down = (Button)tableLayoutPanel1.GetControlFromPosition(cp.Column, cp.Row + 1);
//etc
}
Dont' forget to check if column/row is not null before subtracting 1
Upvotes: 1
Reputation: 5373
You could set the Tag property to the numbers then in the common click method you can something like:
int i = Math.Floor(((int)sender.Tag) / 10);
int j = ((int)sender.Tag) - i;
Or you could use arrays.
Upvotes: 0