SajidBp SajidBp - 10 days ago 6
Vb.net Question

How to handle click event of button using add handler,remove handler

I have go through Google,and different sites,to get the answer of add handler,remove handler.
As per Documentation on Msdn,to handle an event that fired on different scenario,we use AddHandle to link methods with click event.(may i got it wrong way).
LET i have a Button Click Event,i want to link it with a method,

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

End Sub


and method is

Sub EventHandler()
' Handle the event.
MsgBox("EventHandler caught event.")
End Sub


how can i handle them when both above are in same class,or in different class.
can i do this.

AddHandler Button1.Click, AddressOf EventHandler()
RemoveHandler Button1.Click, AddressOf EventHandler()


,please guide me in proper way.

Rex Rex
Answer

Event can be subscribed in two ways:

  1. direct handling (when your control, a button in your example, is declared as WithEvents), and it will be triggered always:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
       ' Some action
    End Sub
    
  2. dynamically subscribe/unsubscribe events, for example:

    Sub test()
    
      ' Subscribe the handlers based on some criteria
      If True Then
          AddHandler Button1.Click, AddressOf EventHandler1
      Else
          AddHandler Button1.Click, AddressOf EventHandler2
      End If
    
    End Sub
    
    
    Sub EventHandler1(sender As Object, e As EventArgs)
    
      ' some action
    
      ' if you wish to unsubscribe the event, do below
      RemoveHandler Button1.Click, AddressOf EventHandler1
    
    End Sub
    
    Sub EventHandler2(sender As Object, e As EventArgs)
    
      ' some other action
    
      ' if you wish to unsbuscribe:
      RemoveHandler Button1.Click, AddressOf EventHandler2
    
    End Sub
    

Note:

  1. you can subscribe to the event to multiple handlers

  2. your handler have to match the signature of Handler(Sender as object, e as EventArgs)