.net – How to write event handler in VB.NET?

.net – How to write event handler in VB.NET?

Writing the handler method is simple – just write a Sub which takes no parameters and displays a message box.

You then need to subscribe the handler to the event, which you can either do adding a Handles clause to the method:

Sub ShowMessageBox() Handles foo.TestEvent

Or by using an AddHandler statement:

AddHandler foo.TestEvent, AddressOf ShowMessageBox

Note that to follow .NET conventions, your delegate should have two parameters – one of type Object to specify which object raised the event, and one of type EventArgs or a subclass, to provide any extra information. This isnt required by the language, but its a broadly-followed convention.

In VB, we have two methods to subscribe the event of Publisher class.

Delegate
Public Delegate Sub TestEventDelegate()

Event publisher class that publishes and raises an event

Public Class EventPublisher
    Private _num As Integer
    Public Event NumberChanged As TestEventDelegate
    Public Property Number As Integer
        Get
            Return _num
        End Get
        Set(value As Integer)
            _num = value
            RaiseEvent NumberChanged()
        End Set
    End Property
End Class

Event subscriber class

Public Class EventSubscriber
    instance of EventPublisher class
    Private WithEvents myObject As New EventPublisher

    Handler of myObject.NumberChanged event
    Public Sub ShowMessage() Handles myObject.NumberChanged
        Console.WriteLine(Value has been changed)
    End Sub

    Shared Sub Main()
        Dim es As New EventSubscriber
        es.myObject.Number = 10
        es.myObject.Number = 20

        Handle the events dynamically using AddHandler
        Dim ep1 As New EventPublisher
        ep1.Number = 101
        Attach an event to the handler
        AddHandler ep1.NumberChanged, AddressOf TestIt
        ep1.Number = 102
    End Sub
    Shared Sub TestIt()
        Console.WriteLine(Number is modified)
    End Sub
End Class

.net – How to write event handler in VB.NET?

Leave a Reply

Your email address will not be published.