使用click事件打印2D Array的索引

时间:2013-01-05 14:16:43

标签: c# visual-studio-2010 multidimensional-array

下面的代码显示每个按钮的索引,当单击按钮在一个数组中时,所有这些都是在表单加载中完成的。但是我想在click事件中做同样的事情,而不是在表单加载中我将如何进行这样做:

图像:enter image description here

代码:

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


        }
    }
}

1 个答案:

答案 0 :(得分:0)

回答如下:

 private void ClickedButton(object sender, EventArgs e)
        {
            Button s = (Button)sender;
            int x = int.Parse(s.Name.Split()[1]);
            int y = int.Parse(s.Name.Split()[3]);

            MessageBox.Show("you have clicked button: " + x +" "+ y);
        }