c# - 事件处理程序和发送者

标签 c# events handler event-handling sender

所以在我的程序中我创建了一个带有按钮和数字值的结构...像这样

struct box
    {
        public int numberValue;
        public Button button;
    }

然后我制作了这个结构的二维数组

box[,] boxes = new box[20, 20];

现在我做的是制作 400 个按钮并将它们分配给数组的每个索引...像这样

        private void createBoxes()
    {
        int positionX;
        int positionY;
        for (int i = 0; i < 20; i++)
        {
            for (int j = 0; j < 20; j++)
            {
                positionX = 20 + (25 * i);
                positionY = 20 + (25 * j);
                boxes[i, j].button = new System.Windows.Forms.Button();
                boxes[i, j].button.Location = new System.Drawing.Point(positionX,positionY);
                boxes[i, j].button.Size = new System.Drawing.Size(25, 25);
                this.Controls.Add(boxes[i, j].button);
                boxes[i, j].button.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
                boxes[i, j].button.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                boxes[i, j].button.Visible = true;
                boxes[i, j].button.Name = "button";
                boxes[i, j].button.Click += new EventHandler(buttonClick);
            }
        }
    }

现在,当我创建事件处理程序时,我想发送“boxes[i,j]”而不仅仅是“boxes[i,j].button”,是否可以这样做?

最佳答案

除了定义您自己的匿名事件处理程序之外,还有一种简单的方法可以执行您想要的操作:

boxes[i, j].button.Tag = boxes[i, j];

然后:

private void buttonClick(object sender, EventArgs e)
{
    var box = ((Button)sender).Tag as box;
}

关于c# - 事件处理程序和发送者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5798205/

相关文章:

c# - Entity Framework 、WCF、客户端和对象上下文问题

Android ACTION_DOWN 事件在几秒后自动执行 ACTION_UP 事件

android - Handler.postDelayed 有超时吗?

java - ScrollView 内容更新

c# - C# 中 Math.Sin() 和 Math.Cos() 的精度

c# - MVVM MEF WindowFormHost

c# - 如何制作通用类型转换方法

c# - LongListMultiSelector 阻止所选项目的手势事件

javascript - 仅当两个输入都模糊时触发某些内容

php - Laravel 没有报告 Handler.php 的报告方法的所有异常