Event for Click in any button (C# windows forms)

前端 未结 4 1403
广开言路
广开言路 2020-12-21 03:35

I\'m developing a program that has many buttons that should do a similar action when clicked, but with a small difference based on which button was clicked. The problem is t

4条回答
  •  忘掉有多难
    2020-12-21 04:00

    Yes you can create just one Button Click Event Handler and hook it up with all the buttons using visual studio designer.

    It is simple, just follow these steps:

    1) Create btn_click event handler for any one button by double clicking on any button. 2) For all other buttons, right click on any button, click properties, go to events, on "Click" event, select btn_click from the drop-down list.

    If you want different functionality in different buttons in same event handler, you can downcast the sender parameter to Button type and then use its Name property to differentiate among buttons.

    Here's an example:

    private void btn_Click(object sender, System.EventArgs e)
    {
       Button b =(Button)sender;
       if(b.Name == "button1")
       {
          //some code
       }
       else if(b.Name == "button2")
       {
          ....
       }
    }
    

提交回复
热议问题