Add events to controls added dynamically

前端 未结 2 787
后悔当初
后悔当初 2020-11-30 07:59

I am working on winform app. and I have added some controls dynamicaly eg. Button now i want to add an event to that created button, how can i perform this? als

相关标签:
2条回答
  • 2020-11-30 08:18

    I totally agree with Darin's answer, and this is another syntax of adding dynamic event

    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");
    }
    
    0 讨论(0)
  • 2020-11-30 08:34
    // 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);
    
    0 讨论(0)
提交回复
热议问题