sef
sef

Reputation:

variable button vb.net

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?

Upvotes: 0

Views: 1362

Answers (3)

Jason Down
Jason Down

Reputation: 22211

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.

Upvotes: 3

Michael Buen
Michael Buen

Reputation: 39483

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

Upvotes: 2

lc.
lc.

Reputation: 116538

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))

Upvotes: 3

Related Questions