how to execute click event on dynamically created button in c#.net

后端 未结 1 1404
慢半拍i
慢半拍i 2021-01-14 05:32

I am trying to build an app, where user can select category and according to it displays its sub categories , these sub categories are buttons, which are dynamically created

相关标签:
1条回答
  • 2021-01-14 06:01

    you can put all your logic into one handler:

    System.Windows.Forms.Button b = new System.Windows.Forms.Button();
    b.Click += new EventHandler(b_Click);
    //finally insert the button where it needs to be inserted.
    ...
    
    void b_Click(object sender, EventArgs e)
    {
        MessageBox.Show(((System.Windows.Forms.Button)sender).Name + " clicked");
    }
    

    To your edit:

    You are storing the reference for your button(s) inside the Field btnDynamicButton. Hence it always gets overwritten with the latest button you have created. You should not reference the button by using a field. The sender parameter of the click-handler contains the button element that has been clicked. See the code above: Simple cast sender to Button and you know which button has been clicked:

    private void btnclick_Click(object sender, EventArgs e)
    {
       Button btn = (Button)sender
       label2.Text = btn.Text;
    }
    
    0 讨论(0)
提交回复
热议问题