How to add event handler for dynamically created controls at runtime?

With anonymous method:

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 
                    };

With lambda syntax for an anonymous method:

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

With method:

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

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

Further information you can find in the MSDN Documentation.

Leave a Comment