0

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

图片:在此处输入图像描述

代码:

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


        }
    }
}
4

1 回答 1

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);
        }
于 2013-01-05T14:44:21.727 回答