繁体   English   中英

如何将按钮的索引传递给事件处理程序?

[英]How to pass an index of a button to an EventHandler?

很高兴知道我刚刚开始编程,所以 go 对我来说很容易;)

在我的程序中,我制作了一个由多个按钮( btn[i, j] )组成的面板,我使用两个 for 循环创建了这些按钮。 这些按钮被赋予一个坐标对/索引[i, j] ,然后我将其传递给一个名为valueBtn的二维数组,并在相应的索引上为该坐标对赋予一个值。

        public void board(object obj, EventArgs ea)
        {
            int n = 6;
            Button[,] btn = new Button[n, n];
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    int p = 60 * i + 100;
                    int q = 60 * j + 100;
                    btn[i, j]          = new Button();
                    btn[i, j].Location = new Point(p, q);
                    btn[i, j].Size     = new Size(60, 60);

                    int[,] valueBtn = new int[n, n];
                    valueBtn[i, j]  = 0;

                    this.Controls.Add(btn[i, j]);
                }
            }
            btn[i, j].Click += btnPress;
        }

接下来我有一个新方法btnPress链接到 EventHandler btn[i, j].Click 目的是在这个方法中我找出哪个按钮被按下,哪个坐标/索引属于这个,这样我就可以在二维数组valueBtn中找到相应的值,并最终在新的 function drawValue中绘制这个值。

        public void btnPress(object sender, EventArgs ea)
        {
            Button pressedBtn = sender as Button;
            // Here I want to know which button is pressed and the index [i,j] of the button
            // so that I can find the value that belongs to the button in the 2d valueBtn array
            .
            .
            .
            this.Paint += drawValue;
        }

我已经尝试了很多关于 EventHandler 的引用,但我就是想不通。

非常感谢您的时间和帮助!

您可以设置每个按钮的Text属性,例如btn[i, j].Text = some ij combination 然后像这样在btnPress方法中获取它string s = (sender as Button).Text; . 你也可以使用Tag属性,所以基本上概念是一样的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM