How can I make a single event handler handle ALL Button.Click events?

You can modify the Handles clause on the VS generated event code so that it can process the same event for multiple controls. In most cases, someone might want to funnel most, but not all, button clicks to one procedure. To change the Handles clause:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button1.Click, 
                 Button3.Click, Button4.Click ...
    ' just add the extra clicks for the additional ones

    ' you will need to examine "Sender" to determine which was clicked

    ' your code here
End Sub

This can also be done dynamically, such as for controls which are created and added to a form in the Load event (or where ever):

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddHandler Button1.Click, AddressOf AllButtonsClick
    AddHandler Button2.Click, AddressOf AllButtonsClick
    AddHandler Button3.Click, AddressOf AllButtonsClick

End Sub

To literately wire all buttons to the same event, you can loop thru the controls collection (uses Linq):

For Each b As Button In XXXXX.Controls.OfType(Of Button)
     AddHandler b.Click, AddressOf MyClickHandler
Next

Where XXXXX might be Me or a panel, groupbox etc – wherever the buttons are.

Leave a Comment