C# equivalent to VB.NET 'Handles button1.Click, button2.Click'

后端 未结 6 1032
抹茶落季
抹茶落季 2021-01-12 08:15

In VB.NET I can do

private sub button_click(sender, e) handles Button1.Click, Button2.Click etc...
do something...
end sub
相关标签:
6条回答
  • 2021-01-12 08:27

    C# does not have the Handles keyword.
    Instead, you need to add the handlers explicitly:

    something.Click += button_click;
    somethingElse.Click += button_click;
    
    0 讨论(0)
  • 2021-01-12 08:31
    btn1.Click += button_click;
    btn2.Click += button_click;
    

    is the answer

    0 讨论(0)
  • 2021-01-12 08:36
    Button1.Click += button_click;
    Button2.Click += button_click;
    
    0 讨论(0)
  • 2021-01-12 08:38

    Manually, you can do this:

    button1.Click += button_Click;
    button2.Click += button_Click;
    ...
    

    In the Designer, the Click event property is actually a drop-down menu where you can choose among existing methods that have the appropriate signature.

    0 讨论(0)
  • 2021-01-12 08:43

    Try this:

    button1.Click += button_click;
    button2.Click += button_click;
    
    0 讨论(0)
  • 2021-01-12 08:44

    If you want to keep it maintainable, I would go with something like this:

    //btnArray can also be populated by traversing relevant Controls collection(s)
    Button[] btnArray = new Button[] {button1, button2};
    foreach(Button btn in btnArray) {
      btn.Click += button_Click;
    }
    

    Any refactoring to this code is done via a single point of maintenance. For example:

    • You decide to bind to a custom button class with a custom event, i.e. MyClick.
    • You decide to change logic of how buttons are collected, add or remove buttons.
    • You figure button_Click is a bad name, or need to have conditional event binding.
    0 讨论(0)
提交回复
热议问题