Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an event handler for a programmatically created object in VB.NET?

Tags:

Say I have an object that I dynamically create. For example, say I create a button called "MyButton":

Dim MyButton as New Button() MyButton.Name = "MyButton" 

How do I create, say, a "Click" event? If it were statically created I could create a function as:

Private Sub MyButton_Click(ByVal sender as system.object, ByVal e As System.EventArgs) Handles. 

How do I implement an event handler for MyButton?

like image 240
GregH Avatar asked Sep 03 '11 06:09

GregH


People also ask

How do you create event handlers with visual studio net?

From the Class Name drop-down list at the top of the Code Editor, select the object that you want to create an event handler for. From the Method Name drop-down list at the top of the Code Editor, select the event. Visual Studio creates the event handler and moves the insertion point to the newly created event handler.

How do you call an event handler in VB net?

Call an event handler using AddHandler Make sure the event is declared with an Event statement. Execute an AddHandler statement to dynamically connect the event-handling Sub procedure with the event. When the event occurs, Visual Basic automatically calls the Sub procedure.


1 Answers

You use AddHandler and AddressOf like this:

Dim MyButton as New Button() MyButton.Name = "MyButton" AddHandler MyButton.Click, AddressOf MyButton_Click 

There is more info here in the MSDN documentation:

  • How to: Add an Event Handler Using Code
like image 167
Rick Sladkey Avatar answered Nov 08 '22 06:11

Rick Sladkey