Loading...
 
JoiWiki » Developer » .Net » .Net Theory » VB.Net Event Patterns VB.Net Event Patterns

VB.Net Event Patterns

Event Patterns in VB.Net

Events in VB.Net are comparatively simply when considered alongside the C# conventions. The below shows how an event is declared within a class, showing the name of the event (Message) and the signature within the parenthesis:

Event Message(ByVal Message As string)

 

This event can then easily be called from within the class by using the following syntax:

RaiseEvent Message("Here's a message!")

 

From there any calling class/object will be able to subscribe to this event sender by setting up a handling sub (functions are not permitted here as a value cannot be passed back to an event in this way). Here is a quick example of an event sender and associated handler:

Public Class Subscriber
    Dim WithEvents SendR As new Sender()
    Public Sub SendR_MessageHandler(ByVal Message as string) handles SendR.Message
        Messagebox.Show(Message)
    End Sub
End Class

Public Class Sender
    Event Message(ByVal Message as string)

    Public Sub FireEvent()
        RaiseEvent Message("Here's Johnny")
    End Sub
End Class

 

This pattern works fine and will; enable you to fire off events on a number of objects but there are limitations... for example if you were to have a collection of sender objects then the WithEvents keyword would not be appropriate (and in fact would be kicked out by the compiler). The way around this issue is to use the AddHandler keyword and create Subs to raise the events that you'd like to use. With this setup yuou're then able to add hanflers for any acdtions before they're added to a collection. Here's a quick example which builds on the code above:

Public Class Subscriber
    Dim SenderList as list(of Sender) = New list(of Sender)
    Public Sub AddSenderToList(SendObj as Sender)
        AddHandler SendObj.Message, AddressOf ReceivedMessage
        SenderList.Add(SendObj)
    End Sub
    
    Public Sub ReceivedMessage(ByVal Message as string)
        Messagebox.Show(Message)
    End Sub    
End Class

Public Class Sender
    Event Message(ByVal Message as string)

    Public Sub FireEvent()
        RaiseEvent Message("Here's Johnny")
    End Sub
End Class

 

 

Created by JBaker. Last Modification: Saturday December 22, 2018 16:19:29 GMT by JBaker.

Developer