Understanding Custom Events using Visual Basic.NET 2005 - Rewriting the sample class with eventing in Visual Basic 2005: coding the class
(Page 3 of 5 )
The following is the class which is rewritten to support events available in Visual Basic 2005. Before trying to understand events, let us go through the following class:
Public Class Sample01
Private _x As Integer
Private _y As Integer
Public Event CalculationStatus(ByVal Msg As String)
Public Property X() As Integer
Get
Return _x
End Get
Set(ByVal value As Integer)
_x = value
End Set
End Property
Public Property Y() As Integer
Get
Return _y
End Get
Set(ByVal value As Integer)
_y = value
End Set
End Property
Public Function GetCalculatedValue() As Double
If Me.Y <> 0 Then
Dim v As Double = Me.X / Me.Y
RaiseEvent CalculationStatus("Successful")
Return v
Else 'division by zero
RaiseEvent CalculationStatus("Division by zero is not permitted")
Return 0
End If
End Function
End Class
Let us try to understand the above class. The following is a new statement in the above class:
Public Event CalculationStatus(ByVal Msg As String)
The above declaration says that "CalculationStatus" is an event (part of "Sample01" class) which may be necessary to handle at the client level (say Windows Form). It carries a message with the "Msg" parameter.
Every event declared within the class must be fired to notify the client (say Windows Form) to handle the latest event. If the event is not fired, the client would never know about its message or progress. To fire an event, "RaiseEvent" will be used. In the above class, we are firing two times in various situations (as part of an "if" condition).
If you drag a button onto Windows Form, you can observe that it has lots of events to handle. But mostly you will handle only the "Click" event. Even the "Click" event is not compulsory to handle. If you don't handle any events, the button simply does nothing. Similarly, with our class, when instantiated, you have the opportunity to handle the "CalculationStatus" event (which is still not compulsory). If the Windows Form handles the event, it gives out the message; otherwise, it does not.
In the next section we try to test the above class with a Windows Form.
Next: Rewriting the sample class with eventing in Visual Basic 2005: testing the class >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee