且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在运行时为动态创建的控件添加事件处理程序?

更新时间:2023-12-06 15:01:34

使用匿名方法:

Button button1 = new Button();
button1.Click += delegate
                    {
                        // Do something 
                    };

使用带有显式参数的匿名方法:

With an anonymous method with explicit parameters:

Button button1 = new Button();
button1.Click += delegate (object sender, EventArgs e)
                    {
                        // Do something 
                    };

使用lambda语法表示匿名方法:

With lambda syntax for an anonymous method:

Button button1 = new Button();
button1.Click += (object sender, EventArgs e) =>
                    {
                        // Do something 
                    };

使用方法:

Button button1 = new Button();
button1.Click += button1_Click;

private void button1_Click(object sender, EventArgs e)
{
    // Do something
}

您可以在 MSDN文档