0

好的,假设我们有按以下形式排列的按钮 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]

例如,如果我单击按钮 34,来更改按钮 24、44、33 和 35 的颜色。问题是当我单击按钮返回任何这些值时,我不知道该怎么做. 拿一个我想做的伪代码。

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

因此,当我按下一个按钮时,我需要以某种方式获取该按钮的值 i、j 并且我可能会处理相同样式的其他按钮(i +1、j 等)

我可以分别对待每个按钮......

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
}

,.....但是我有 25 个按钮,我不想在所有 25 个键中编写相同的代码。

我想要的是:

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

原谅我的英语不好。

4

2 回答 2

1

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

于 2013-02-24T20:56:25.723 回答
0

您可以将 Tag 属性设置为数字,然后在常见的单击方法中,您可以执行以下操作:

int i = Math.Floor(((int)sender.Tag) / 10);
int j = ((int)sender.Tag) - i;

或者你可以使用数组。

于 2013-02-24T20:45:38.030 回答