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

前端 未结 3 571
独厮守ぢ
独厮守ぢ 2020-11-28 15:34

I am working on C# windows application. my application get controls(button,text box,rich text box and combo box etc)from custom control library and placed them into form dyn

3条回答
  •  执笔经年
    2020-11-28 16:05

    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.

提交回复
热议问题