【问题标题】:How to attach Click event dynamically to multiple buttons?如何将 Click 事件动态附加到多个按钮?
【发布时间】:2020-06-11 19:31:46
【问题描述】:

我正在尝试用 C# 开发基诺游戏,所以我有 80 个按钮,每个按钮都有 1-80 的数字,如下所示:

所以我想做的是每个用户应该选择 10 个数字(不是更少,不是更多),当单击按钮时,按钮的背景颜色变为绿色,但我想知道如何做到这一点无需在每个按钮上调用事件。这些数字应该保存在数据库中。

我尝试在数组上添加按钮并像这样循环遍历数组:

var buttons = new[] { button1, button2, button3, button4, button5, ..... };
foreach (var button in buttons)
{
    if (button.Focused)
    {
        button.BackColor = Color.Green;
    }
}


【问题讨论】:

  • 您可以使用 Tag 属性来存储每个按钮的编号,并为所有按钮设置一个事件。当事件被调用时,您可以根据标签知道按下了哪个按钮,您可以将数据保存在数据库中并更改颜色。
  • 那么,您是在运行时动态创建 80 个按钮,而不是在设计时在表单上放置 80 个单独的按钮?你想知道如何给他们每个人一个点击事件?
  • 我假设这是 Visual Studios 中的 Windows 窗体,对吗?

标签: c# winforms button


【解决方案1】:

您可以为每个按钮分配相同的事件处理程序:

foreach (var button in buttons) {
    button.Click += (sender, e) => {  
        ((Button)sender).BackColor = Color.Green;
    };
}

如果要添加到表单上的所有按钮,可以在表单构造函数中调用:

int counter = 0;
public Form1()
{
    InitializeComponent();
    foreach (var c in Controls)
    {
        if (c is Button)
        {
            ((Button)c).Click += (sender, e) =>
            {
                if (counter >= 10) return;
                Button b = (Button)sender;
                b.BackColor = Color.Green;
                counter += 1;
            };
        }
    }
}

【讨论】:

  • 我应该在哪里称呼它?我应该将其作为一种方法,然后将其调用到事件中还是如何?
  • 无论您在何处创建按钮。创建它们后立即添加。或者,如果按钮是在设计器中创建的,您可以在表单构造函数中添加它 - 在 InitializeComponent(); 之后。
  • 是的,按钮是在设计器中创建的,但我无法在问题部分附加图片。
  • 我已经更新了答案以显示如何添加到所有按钮。
  • 如何验证,让每个用户应该准确选择 10 个按钮?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多