Events – Visual Basic.NET Tutorial

Modern applications don’t run from start-to-finish, in a linear fashion. Instead, they must respond to user input, system events, and network requests. For example, a document-based application must update the document when the user types a letter. Similarly, a Web service must wait for an incoming Web request, process the request, and return the response.

The .NET Framework uses events to handle each of these scenarios. For example, if a user clicks a button, the .NET runtime raises the Button.Click event. To run code when a user clicks a button, create a method, and assign it to handle the Button.Click event.

When creating custom classes, you might need to define events that other applications can handle. For example, if you create a multi-threaded process that can run in the background, you would need to create an event that is called when the processing completes.

At the end of this lesson, you will be able to:

  • Respond to events
  • Raise events

Generating Events in Visual Studio

In this video, I describe how events work in the .NET Framework (transcript below):

Anything can initiate an event; it’s really up to the class. One of the most common events that you’ll work with is the Button.Click event.

The Button.Click event is initiated when the user clicks a Button. When that happens, the Button class raises the Click event. In turn, the .NET Framework Common Language Runtime (CLR) calls any methods that have added themselves as event handlers.

In Visual Basic, that is done with the AddHandler keyword. In C#, that is done with the += operator.

Automatically Generating Event Handlers with Visual Studio

This video shows you how to use Visual Studio to automatically generate event handlers (with the transcript below):

Most of the time, when you’re responding to an event, you’ll be responding to events initiated by graphical controls. The Visual Studio user interface makes it easy to generate methods that respond to events for controls. Simply click the control, select Events in the Properties pane, and then double-click the event you want to respond to. You’ll see that Visual Studio automatically generates the method header for you. All you need to do is write the code.

Visual Studio works exactly the same when developing in Visual Basic.

Now, I’ll demonstrate how the application runs. Click the button, and it runs the method that I typed, which was simply to display a message box that showed, “Hello, world”.

How to Manually Create Event Handlers

If you need to manually create an event handler, follow these steps:

1. Examine the delegate for the event to determine the parameters that the event handler must accept. For .NET Framework classes, you can look up the event in MSDN. Typically, event handlers must return void and accept two parameters: an Object and an EventArgs (or a derived class). The following code sample demonstrates a delegate:

Public Delegate Sub AlarmEventHandler(sender As Object, e As EventArgs)

2. Create the method that will handle the event.

3. Add the event handler to link the event and the method you created.

Public Sub Button1_Click(sender As Object, e As EventArgs)

     ' Method code 

End Sub 

AddHandler Me.Button1.Click, AddressOf Me.Button1_Click

How to Raise Events

In this video, I demonstrate how to raise events in Visual Basic.NET and Visual Studio. The transcript follows:

You can create classes that raise events. Often, you’ll do this when your class is a control that the user interacts with. For example, your class is a Button control that the user can click, raising the Click event. There might be other events as well, like the OnMouseOver event, which is called when the mouse passes over the control.

The second common reason to raise an event is when a class is asynchronous. With an asynchronous class, the calling method will call a member method that performs a long-running calculation. Your class does the work in the background, returning control to the calling method. When the calculation is complete, your class raises an event, and the calling method retrieves the results by handling the event.

I’ll show you how to create a simple class that raises an event.

I’m going to create a class called MyCalc that performs a calculation when the calling method calls a member method. Instead of returning it the conventional way, it’s going to return it by raising an event.

The first thing we need to do is to create a delegate for the event. You do that in Visual Basic using the Delegate keyword. I’m going to call this KnowAnswer. I’m going to provide two parameters: the standard Object, which represents the method that sent it, and an instance of AnswerEventArgs.

Now i’m going to create the AnswerEventArgs class. Notice that it’s inheriting fromt he standard EventArgs class. It’s going to have a single public member called answer. It’s an integer, and i’ll populate that value by adding two values provided to my method.

I’m creating the MyCalc class now. First I’m declaring the event using the delegate. I’m going to name the event OnKnowAnswer, and there’s the name of my delegate, KnowAnswer.

Now I’m going to create a method called Add that adds two integers. I’m going to use those two integers to populate the answer member of an instance of AnswerEventArgs. First I’m going to create an instance of AnswerEventArgs with the name e.

Next I will set the value of e.answer to the sum of the i1 and i2 integer parameters.

Now that we’ve created that instance and populated the answer, I can actually call the event by using the RaiseEvent keyword and specifying the OnKnowAnswer event that I declared.

I’m providing two parameters: Me and e. Me represents the instance of the class itself, and e represents my instance of AnswerEventArgs. Now I just need to create an instance of MyCalc and call the Add method to raise the event. Raising the event will call my event handler.

Now I am using the AddHandler keyword to declare the event handler that I will declare next.

I’m naming the event handler mc_OnKnowAnswer which is the standard convention.

I’m calling Add with two integers, and then calling the Console.Readkey, which stops the debugger from closing the window so we can see the results.

Now I’m declaring the subroutine mc_OnKnowAnswer which will act as our event handler. Notice that I need to add the Object and AnswerEventArgs parameters exactly as they appear in the delegate. Those must match exactly.

In the event handler I’m going to have a single line that displays the results to the console by calling Console.WriteLine.

Now to run the application and demonstrate that it runs properly. If this works, we shoudl see the answer of 8–the sum of 5 plus 3. Great!

Return to the .NET Framework Fundamentals Table of Contents.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>