我们在运行时创建了许多按钮作为匿名对象.我们可以在这些按钮上添加一个 onlick 事件吗?



正如标题所说,我在事件发生后将按钮创建为匿名对象(单击另一个按钮)。我正在尝试做的是使此按钮在单击时显示消息框。我无法将此功能添加到按钮中,也没有找到任何可以解决我的问题的方法。也许它不能以这种方式发生。

Controls.Add(new Button { Size = new Size(50, 50),
    Location = new Point(40 + i * 60, 100),
    Text = i.ToString(),
    BackColor = c,
    //eventforshowingmessage()
 });`

您可以先将按钮分配给变量,然后注册事件:

   public AddButton()
    {          
        var newButton = new Button { Text = "Button 1" };
        newButton.Click += MyEventListener;
        this.Controls.Add(newButton);            
    }
    private void MyEventListener(object sender, EventArgs e)
    {
        var button = (Button)sender;
        MessageBox.Show($"{button.Text} says: Hello, world");
    }

我建议使用不同的语法Parent而不是Controls.Add

 for (int i ....) { // whatever loop
    ...
    new Button {
      Size = new Size(50, 50),
      Location = new Point(40 + i * 60, 100),
      Text = $"{i}", // May appear more readable than i.ToString()
      BackColor = c, 
      Parent = this, // <- instead of this.Controls.Add
    }.Click += eventforshowingmessage;
    ...
  }

演示:例如,让我们创建5按钮并显示单击了哪个按钮:

  for (int i = 0; i < 5; ++i) {
    new Button {
      Size = new Size(50, 50),
      Location = new Point(40 + i * 60, 100),
      Text = $"{i}", 
      BackColor = SystemColors.Control,
      Parent = this, 
    }.Click += (ss, ee) => {
      // Lambda: what shall we do on click
      MessageBox.Show($"{(ss as Control).Text} clicked!");
    };
  }

相关内容

最新更新