Technical Training
VB.NET 2005Event Handling In Visual Basic .NET Page - 2
Event Handling In Visual Basic .NET
Handling Events by attaching a delegate
A delegate is kind of OO function pointer that permits a function to be invoked indirectly by making reference to the function. They are employed to attach to event handlers and pass a procedure from on procedure to another. However delegates can also be used for other tasks not related to events like free threading or procedures that need to call different versions of functions at compile time. An illustration on the use of delegates is given by the following codes:
The output is given below:
5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
Delegates are reference type based on the class System.Delegate and are capable of referencing both share methods and instance methods. Using Delegates is particularly advantageous in situations where you need an intermediary between a calling procedure and the procedure being called. In some cases it may be required that when an object raises an event, you may want to raise different event handlers under different circumstances.
In these situations the object that raised the event cannot know in advance, which EventHandler will handle the specific event. These situations are handled well by use of delegates. While creating your own delegates is allowed, Visual Basic creates the delegates in most cases and also manages the details. Thus the Event statement implicitly defines a delegate class which is given a name
It has the same signature as the event and also creates the AddressOf statement implicity. Event Delegates are multicast, in other words they can keep references to more than one event handling method. A delegate serves as an event dispatcher for the class which had raised the event by maintaining a list of registered event handlers for the event.
The AddHandler and Removehandler statements allow you to start and stop event handling at any time during the program execution. Unlike the keyword Hanles which specifies the event handling procedure at design time, the AddHandler statement connects the procedures to events at run time. Addhandler statement invokes the event’s AddHandler accessor for custom events. Let us see and illustration for this:
Sub TestEvents()
Dim Obj As New Class1()
' Associate an event handler with an event.
AddHandler Obj.Ev_Event, AddressOf EventHandler
Obj.CauseSomeEvent() ' Ask the object to raise an event.
End Sub
Sub EventHandler()
' This procedure handles events raised by the object Obj.
MsgBox("EventHandler caught event.") ' Handle the event.
End Sub
Public Class Class1
Public Event Ev_Event() ' Declare an event.
Sub CauseSomeEvent()
RaiseEvent Ev_Event() ' Raise an event.
End Sub
End Class
The next illustration demostrates declaring and consuming events.This code defines the behaviour of Laughing Doll that takes user input to start and stop laugh and to pause laughing. I this case the event is raised on one class and the hadling of the event is done in another class.
Handling Events by overriding protected method of base class
When you inherit from a control or a component, you create a new control or component that incorporates all of the functionality of its base class. Any event handlers that are defined by the base class will be included in the inherited component.
The following example shows a typical event handler:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Static Counter As Integer = 0
Counter += 1
MessageBox.Show(" This button has been clicked " & _
Counter.ToString() & " time(s).")
End Sub
In order to allow this method to be overridden in an inheriting class, you must add the Overridable keyword and change the access level to Protected, Protected Friend, or Public. The following example shows an event handler that can be overridden:
Protected Overridable Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Static Counter As Integer = 0
Counter += 1
MessageBox.Show(" This button has been clicked " & _
Counter.ToString() & " time(s).")
End Sub
Overriding an inherited event handler is the same as overriding any other kind of inherited method, with one important difference: When you override an inherited event handler, you have to remove the Handles clause.
To override a method in an inherited component
• Add the Overrides keyword to your method declaration.
Note You should not add a Handles clause to the method. The event handler is already associated with the event in the base class, and this association is passed on to the inheriting class. In other words, the method will be executed when the event is fired and does not require an additional Handles clause.
The following example shows how to override the event handler from the previous example:
Protected Overrides Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Static Counter As Integer = 0
Counter += 1
MessageBox.Show(" This inherited button has been clicked " & _
Counter.ToString() & " times.")
End Sub
The Handles clause is no longer associated with the method. This is not an oversight, but rather an important part of how events are handled in the .NET Framework. The event handler is already associated with the event in the base class, and this association is passed on to the inheriting class. In other words, the method will be executed when the event is fired and does not require an additional Handles clause. Adding an additional Handles clause, as shown below, will create an additional association with the event, and will cause the method to be executed twice per event.
' INCORRECT
Protected Overrides Sub Button1_Click(ByVal sender As System.Object, _
ByVal e as System.EventArgs) Handles Button1.Click
Static Counter as Integer = 0
' This variable will be incremented twice each time the button is clicked.
Counter += 1
' The message box will be displayed twice for every time the button is clicked, and will display 'inaccurate information.
MessageBox.Show (" This inherited button has been clicked " & _
Counter.ToString() & " times.")
End Sub
This problem caused by overriding event handlers might not be intuitive and can lead to bugs that are difficult to isolate. Setting the appropriate associations with your event handlers is very important. Use caution, and be aware of event associations that are already in place.
VB.NET 2005
- VB.NET 2005 Free Training
- The .NET Framework Architecture Part 1
- The .NET Framework Architecture Part 2
- Application Class and Message Class
- Implementing Class Library Object
- Visual Studio.NET Namespaces
- .NET Assemblies
- Differences between VB.NET 1.0 and VB.NET 2.0
- Introducing VB.NET Windows Forms
- Visual Studio Windows Forms Designer
- Exploring the Forms Designer generated code
- Setting and Adding Properties to Windows Form
- Implementing Inheritance
- Event Handling In Visual Basic .NET
- Building Graphical Interface elements
- .NET Common Windows Forms Controls Part 1
- .NET Common Windows Forms Controls Part 2
- Common Controls and Handling Control Events
- DomainUpDown and NumericUpDown Controls
- Dialog Boxes in Visual Basic .NET
- Visual Studio Adding Controls to Windows Form
- VB.NET Validation Controls
- Working with Menu Controls
- VB.NET MDI Applications
- .NET Exceptions
- VB.NET Creating and Managing Components Part 1
- VB.NET Creating and Managing Components Part 2
- Simple Data Binding
- .NET Complex Data Binding
- .NET Data Form Wizard
- Data Manipulation with ADO.NET
- SQL Server Stored Procedures
- SQL Server Ad Hoc Queries
- Finding and Sorting Data in DataSets
- ADO.NET Object Model
- Working with DataSets
- Using XML Data
- Working with File System in .NET
- Creating Web Service
- Instantiating - Invoking Web Services, Creating Proxy Classes with WSDL
- Web Reference and Web Services
- Web Services - SOAP, WSDL, Disco and UDDI
- Web Application Testing in VB.NET 2005
- Web Application Tracing and Debugging
- Working with Legacy Code and COM Components
- ActiveX Controls and Legacy Code
- Windows Application Testing
- VB.NET Windows Application Testing
- Tracing VB.NET Windows Application
- Debugging Windows Applications In Visual Studio.NET 2005
- Deploying Windows Applications In Visual Studio.NET 2005
- Customizing Setup Project in Visual Studio.NET 2005
- Shared Assembly
- Microsoft .NET Creating Installation Components
- The Registry Editor in Visual Studio.NET 2005
- The File Types Editor







