Create your first Event in Visual Basic
How to create your own events in visual basic?
Many times, you know how to use events. For example, you put a button inside a window Form. By double-clicking the button inside the form designer, you get a function with the keyword Handles at the end of your function.
Events are very useful to execute a method from an action or an external event. But what if you want to create your own event?
Here is a simple article on how to create an event from scratch starting from the easiest way to make one followed by a more practical example.
The simple way to create an event:
First of all, let’s make a basic project to run our tests. Create a basic Windows Application form in Visual Basic. Name your project. Put a TextBox and a Button. Double-click your button and you should have something like this:
Public Class Form1 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click End Sub End Class |
Now, I want to create a simple class called FileClass. Inside that class, there will be a simple method to create a file. Inside the method CreateFile, make sure you put enough protection and verification. If you check if the file path is not empty and not zero, the class should look like this:
Public Class FileClass Public Sub CreateFile(ByVal sPath As String) If sPath IsNot Nothing AndAlso sPath.Length > 0 Then If Not IO.File.Exists(sPath) Then IO.File.Create(sPath) Else MsgBox(sPath & " EXIST" & vbCrLf & "THIS PROGRAM CAN'T OVERITE EXISTING FILES)", MsgBoxStyle.Exclamation) End If End If End Sub End Class |
I used the very basic function from the System.IO; there is nothing very special in that line.
Adding the events
An event is a simple variable with one keyword: Event. Your event could be public or private. In my example, I will create one single even to make this very easy. I will make a public even inside my FileClass and named it FileCreated. Here is what your class will look like: (in yellow, the new lines I added)
Public Class FileClass 'declare your event here Public Event FileCreated() Public Sub CreateFile(ByVal sPath As String) If sPath IsNot Nothing AndAlso sPath.Length > 0 Then If Not IO.File.Exists(sPath) Then IO.File.Create(sPath) Else MsgBox(sPath & " EXIST" & vbCrLf & "THIS PROGRAM CAN'T OVERITE EXISTING FILES)", MsgBoxStyle.Exclamation) End If End If End Sub End Class |

After clicking FileCreated, Visual Studio creates a new sub automatically with the keyword Handle at the end. Your code should look like this. You will find out that there is nothing coming from nowhere. Everything is from your code.
Public Class FileClass 'declare your event here Public Event FileCreated() Public Sub CreateFile(ByVal sPath As String) If sPath IsNot Nothing AndAlso sPath.Length > 0 Then If Not IO.File.Exists(sPath) Then IO.File.Create(sPath) Else MsgBox(sPath & " EXIST" & vbCrLf & "THIS PROGRAM CAN'T OVERITE EXISTING FILES)", MsgBoxStyle.Exclamation) End If End If End Sub Private Sub FileClass_FileCreated() Handles Me.FileCreated MsgBox("FileCreated Event triggered") End Sub End Class |
Inside that class and that Sub method, you could put anything you want. I choose to put a simple message box with a little message inside.
But to make you event work, you need to place a little call function to raise the event using the keyword RaiseEvent. To make this very simple, I decided to place it inside and at the end of CreateFile. It should look like this. By the way, some people might call it as an interrupt event. An electronic guy like me will call those types of events as IRQ for Interrupt Request.
Public Class FileClass 'declare your event here Public Event FileCreated() Public Sub CreateFile(ByVal sPath As String) If sPath IsNot Nothing AndAlso sPath.Length > 0 Then If Not IO.File.Exists(sPath) Then IO.File.Create(sPath) Else MsgBox(sPath & " EXIST" & vbCrLf & "THIS PROGRAM CAN'T OVERITE EXISTING FILES)", MsgBoxStyle.Exclamation) End If End If RaiseEvent FileCreated() 'add the trigger (interrupt) End Sub Private Sub FileClass_FileCreated() Handles Me.FileCreated MsgBox("FileCreated Event triggered") End Sub End Class |
If you create your object and call your CreateFile method, you will have a Message Box after the file been created.
Public Class Form1 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim oFileClass As New FileClass oFileClass.CreateFile(TextBox1.Text) End Sub End Class |
What is the advantage of doing this?
When your event calls a function inside a class, you could easily make a default behavior for your class. Here is an example of an Enhanced Button inherited from a basic button. Inside the class, there is a default MouseHover event for that button. That button changes color when the cursor is over it.
AddHandler is a more practical way to use an event.
You are now capable to make an Event. Good for you. But making an event like the previous page is not very practical because you can’t manage the events. Normally, you want to start and stop your Events. You want to control your program actions.
With the previous example with the class FileClass inside the Form1, let’s make sure the Form1 handles and controls the events from FileClass.
Here is a small modification of my Form1:
Public Class Form1 Private oFileClass As New FileClass 'i know i put NEW here Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click oFileClass.CreateFile(TextBox1.Text) End Sub End Class |
I simply place my declaration outside my Button1 method. That way, everything inside my Form1 could access my FileClass Object. Right now, if you execute your program, there will be not significant changes. Everything should work the same way.
Now I will add method inside my Form1. Inside of that method will have a simple MsgBox. I decided to name that Sub myCreateFile().
Public Class Form1 Private oFileClass As New FileClass 'i know i put NEW here Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click oFileClass.CreateFile(TextBox1.Text) End Sub Private Sub myCreateFile() MsgBox("Create file for the user") End Sub End Class |
Again, if you start your program, there will be nothing special. Now, the good part starts. Only if your class object with Events is created, you could use the AddHandler to make an event at runtime programmatically. AddHandler is a function inside visual basic that tells your program this:
“From now on, if my object does something, then call my function.”
Public Class Form1 Private oFileClass As New FileClass 'i know i put NEW here Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click oFileClass.CreateFile(TextBox1.Text) End Sub Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load AddHandler oFileClass.FileCreated, AddressOf myCreateFile End Sub Private Sub myCreateFile() MsgBox("Create file for the user") End Sub End Class |
The Addhandler keyword used inside the Load form simply telling your program that each time FileCreated is triggered, call myCreateFile. That way and in some way, you are giving the impression that the form controls the FileClass Object.
If you start your program, the myCreateFile will be ready because the handler is created inside the load function. If you press the Button1 to call your CreateFile method from your object, you will notice that there will be two message boxes. The first one will be from your class and the other one will be coming from your Form1.
Important: You could add multiples Addhandler for the same events. For example:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 'this line activate myCreateFile base from oFileClass.FileCreated 'anytime from now on. AddHandler oFileClass.FileCreated, AddressOf myCreateFile AddHandler oFileClass.FileCreated, AddressOf myCreateFile2 AddHandler oFileClass.FileCreated, AddressOf myCreateFile3 End Sub |
RemoveHandler :
Each AddHandler register an event inside your program. You could unregister you Events using the same syntax than the AddHandler. If you want to unregister all events from a object, you need to unregister all of them one by one.
For example: (the order is not important)
RemoveHandler oFileClass.FileCreated, AddressOf myCreateFile RemoveHandler oFileClass.FileCreated, AddressOf myCreateFile2 RemoveHandler oFileClass.FileCreated, AddressOf myCreateFile3 |
Throw exception recommendation
Before I end this article, let me give you an advice. Since this type of subject is for intermediate users, I would recommend that every event must be simple, small and error free. This means that in my example shown here, CreateFile inside my FileClass must be very robust and if possible never throw any error. In other words, if I want to raise an event after creating a file, I have to be sure that it will work.
Your code must execute very quickly too because using AddHandler and RemoveHandler introduce you to asynchronous programming. On the other hand, using Delegate function inside your Form1 (myCreateFile, myCreateFile2, myCreateFile3 …) permits your fonction to be slower and permits bigger calculation.
If you liked my post, please share it to your friends, bookmark it or leave a comment.
Download the sample project here: NewEventSample.zip
References:
my web site: Check Technologies official website
The program I love to use, buy it: Visual Studio 2010 Professional (Old Version)
SQL Server Developer Edition 2012
and Microsoft Visual Studio Pro 2012
are very cheap on Amazon ! Free Delivery. Check here:
SQL Server Developer Edition 2012
0 Response to "How to Create Events in VB.NET"
Posting Komentar