将事件添加到动态添加的控件

sal*_*man 16 c#

我正在使用winform app.我添加了一些动态控件,例如.Button现在我想为该创建的按钮添加一个事件,我该如何执行此操作?也有人可以C#向我推荐一本涵盖winform所有主题的书吗?谢谢.

Dar*_*rov 23

// create some dynamic button
Button b = new Button();
// assign some event to it
b.Click += (sender, e) => 
{
    MessageBox.Show("the button was clicked");
};
// add the button to the form
Controls.Add(b);
Run Code Online (Sandbox Code Playgroud)

  • `+ =`运算符为事件分配处理程序.你应该[阅读有关事件](http://msdn.microsoft.com/en-us/library/aa645739.aspx). (4认同)
  • `=>`表示lambda表达式.你应该[阅读关于lambda表达式](http://msdn.microsoft.com/en-us/library/bb397687.aspx)和[匿名方法](http://msdn.microsoft.com/en-us/library /0yw3tz5k.aspx). (3认同)

Ser*_*glu 15

我完全同意Darin的回答,这是添加动态事件的另一种语法

private void Form1_Load(object sender, EventArgs e)
{
    Button b = new Button();
    b.Click += new EventHandler(ShowMessage);
    Controls.Add(b);
}

private void ShowMessage(object sender,EventArgs e)
{
    MessageBox.Show("Message");
}
Run Code Online (Sandbox Code Playgroud)