How to Code an Event Handler in VB.NET

Lora Covrett

An event refers either to user actions or input from other programs or sources. Event handling varies slightly in VB.NET from the VB 6.0 programming environment. VB.NET allows event handling to be turned on or off at run-time by using "AddHandler" or "RemoveHandler." The program handles the event by performing some action in the "event handler" function or subroutine. The program calls the click event of a "submit" button when the user clicks the "submit" button and the code in the event handler executes.

Step 1

Define a function or a subroutine to handle the click event. "Private Sub MyFunction(ByVal sender As Object, ByVal e As EventArgs) Handles Submit.Click, Send.Click" defines a subroutine where code is placed to react to the click event of the buttons named "Submit" and "Send."

Step 2

Code the appropriate actions to be performed after the click event of the "Submit" or "Send" button. These lines of code are contained within the subroutine called "MyFunction" and will execute each time the buttons are clicked.

Step 3

Use the "AddHandler" statement to associate an event with an event handler if you don't want to use the "Handles" statement shown in Step 1. Within the class, write an event handler subroutine defined as "Submit_Click(ByVal sender as object, ByVal e as EventArgs)." Add the line " AddHandler Submit.Click, AddressOf Submit_Click" when the event occurs.

Step 4

Remove an event handler from an event by coding "Private Sub RemoveMyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteMe.Click RemoveHandler Submit.Click, Addressof RemoveMyButton_Click." This code will prevent the event handling code from executing if the user click on the "Submit" button.

Published by Lora Covrett

I write professionally for several different online publications. My areas of expertise are computer and IT. I enjoy writing about politics as well.  View profile

Comments are disabled on this content.