Understanding Custom Events using Visual Basic.NET 2005 - Rewriting the sample class with eventing in Visual Basic 2005: testing the class
(Page 4 of 5 )
To test the class presented in the previous section, add a new form with two buttons and two labels (one to display the result after division and the other for the message). Modify your code to match the following:
Public Class Form2
WithEvents obj As New Sample01
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
obj.X = 10
obj.Y = 5
Me.lblValue.Text = obj.GetCalculatedValue
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
obj.X = 10
obj.Y = 0
Me.lblValue.Text = obj.GetCalculatedValue
End Sub
Private Sub obj_CalculationStatus(ByVal Msg As String) Handles obj.CalculationStatus
Me.lblMsg.Text = Msg
End Sub
End Class
Usually to instantiate an object, we would write the following:
Dim obj As New Sample01
But to handle events along with instantiation, it should be written as follows:
WithEvents obj As New Sample01
That means "obj" has one or more events to handle and we can handle them as part of our code at the client level. To handle the "CalculationStatus" event of "obj" the following is newly added to the above code:
Private Sub obj_CalculationStatus(ByVal Msg As String) Handles obj.CalculationStatus
Me.lblMsg.Text = Msg
End Sub
When the "RaiseEvent" is executed in the "Sample01" class, the event gets fired and the control automatically executes the above method (say the method which handles the event), which finally displays the message. If you don't write the above method (say you don't handle the event), you simply miss the messages, but the calculation still proceeds.
Next: Handling events dynamically in Visual Basic 2005 >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee