下面的代码在单击按钮时显示每个按钮的索引,这些按钮位于数组中,但所有这些都是在表单加载中完成的。但我想在点击事件中做同样的事情,而不是在表单加载中我将如何继续这样做:
图片:
代码:
namespace _2DArray
{
public partial class Form1 : Form
{
private Button[,] b;
public Form1()
{
InitializeComponent();
b = new Button[2, 2];
b = new Button[,] { {button1,button2 },
{button3, button4}};
}
public int x = 0;
public int y = 0;
private void Form1_Load(object sender, EventArgs e)
{
foreach (Button bt in b)
{
bt.Click += new System.EventHandler(this.ClickedButton);
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
b[i, j].Click += new System.EventHandler(this.ClickedButton);
b[i, j].Name = "X: " + i + " " + "Y: " + j;
}
}
}
private void ClickedButton(object sender, EventArgs e)
{
Button s = (Button)sender;
MessageBox.Show("you have clicked button: " + s.Name);
}
}
}