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

In VB.NET I can do

private sub button_click(sender, e) handles Button1.Click, Button2.Click etc... do something... end sub 

Is there a way to do this in C # .NET? I have about 16 buttons that everyone calls the same function, just passing the button text to the function. I would prefer not to have 16 private void button_clicks calling one function.

I'm not sure how to do this (not very familiar with C #).

+7
source share
6 answers
 Button1.Click += button_click; Button2.Click += button_click; 
+10
source

You can do this manually:

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

In the Designer, the Click event property is actually a drop-down menu in which you can select one of the existing methods that have the corresponding signature.

+7
source

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

 something.Click += button_click; somethingElse.Click += button_click; 
+5
source

Try the following:

 button1.Click += button_click; button2.Click += button_click; 
+4
source

If you want to keep it supported, I would do 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 for this code is done through one service point. For example:

  • You decide to associate custom event buttons with a custom class, i.e. MyClick.
  • You decided to change the logic of how buttons are assembled, added or removed buttons.
  • You see that button_Click is a bad name or needs to be bound to a conditional event.
+2
source
 btn1.Click += button_click; btn2.Click += button_click; 

- answer

+1
source

All Articles