VB.Net - Syntax


In VB.Net the WithEvents keyword
You can declare an object variable using the keyword WithEvents to allow the events from that class to be captured.

WithEvents objButton As System.Windows.Forms.Button 

You must create an instance of this class first.

objMyButton = New System.Windows.Forms.Button 

You can then declare a procedure with the Handles keyword to associate this with a particular event.

Public Sub MyButtonClick(byVal sender As Object, _ 
                           ByVal s As System.EventArgs) Handles objMyButton.Click
End Sub

You cannot create arrays of WithEvents object variables.


In VB.Net he RaiseEvent statement can be used to raise an event previously declared with the Event keyword.
This is the only way to cause an event to actually happen form within a class.

RaiseEvent EventName("Argument") 

This will generate an error if the event has not been declared in the same class.


In VB.Net the AddHandler statement
The AddHandler statement is used to associate an event handler with an event at run time.
The AddHandler statement has the following syntax:

AddHandler object.Event, New EventHandler(AddressOf eventhandler) 

The first argument is the object and the name of the event (for example a control).
The second argument is an expression that evaluates to an EventHandler delegate.

You must create an instance of the class first.

Dim objButton As System.Windows.Forms.Button 
objButton = New System.Windows.Forms.Button

AddHandler objButton.Click, New EventHandler(AddressOf MyButtonClick)

Public Sub MyButtonClick( _
                ByVal sender As Object, _
                ByVal s As System.EventArgs) _
                Handles objMyButton.Click
End Sub

VB.NET lets you dynamically associate event handlers by creating a delegate for you when you call the Addhandler statement.
If you want to handle shared events or events from a class you must use AddHandler.

AddHandler Button1_Click, AddressOf myEventHandler 

Private Sub myEventHandler()
End Sub


RemoveHandler object.eventName, AddressOf delegateInstance 

RemoveHandler Button1_Click, AddressOf myEventHandler 


In VB.Net the AddressOf operator can implicitly create the delegate object for you but this is not recommended.
It is possible to declare an event handler without explicitly creating the EventHandler object.
is this anything to do with multi-threaded ?

AddHandler object.Event, AddressOf Method1 
AddHandler objButton.Click, AddressOf MyButtonClick

Private Sub Method1
   Me.Invoke (New System.Action(AddressOf Method2))
End Sub

You can actually use the AddressOf operator to assign a subroutine to the delegate variable without creating the delegate object explicitely.

Public Delegate Sub MyDelegate(ByVal sArgument As String 
Dim objMyDelegate = AddressOf DebugMsg

Public Delegate Function MyDelegate2(ByVal Name As Object) As String 

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext