views:

222

answers:

3

i declared a global variable button:

Dim button1 As New Button()

Now, i dont know how to add a click event in this button since it is a variable. Do you have any idea how do i do it?

+3  A: 

AddHandler button1.click, AddressOf MyClickEventHandler (MSDN Documentation)

You have to make sure MyClickEventHandler is defined with the same signature as any other Click event handler (i.e. Sub MyClickEventHandler(ByVal sender as Object, ByVal e as EventArgs))

lc
+2  A: 
AddHandler button1.Click, AddressOf MyEventHandler



Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs)
      '
      ' Code to be executed when the event is raised.
      '
      MsgBox("I caught the event!") 
End Sub
Michael Buen
+1  A: 

The Addhandler way is probably the way to go as mentioned. Your other option is to declare your button in the following way:

Dim withEvents button1 As New Button()

Private Sub button1_ClickHandler(ByVal sender As Object, ByVal e As EventArgs) Handles button1.click

'Handle stuff

End Sub

This way simulates what VS does for you if you were to drag the button on the form in the designer.

The advantage to the AddHandler way is that you can remove handlers dynamically as well if you ever needed to.

Jason Down