How can I Raise an Event from a static or Shared method? I get an error saying that I must have an Instance Method to use RaiseEvent.
We have a couple of excellent articles on raising events written by Brian Davis and Bill Ryan on this site, see Brian's Article, but my problem is that I am using a class of Shared methods (would be static in C#) in a VB.NET application. I wanted to use RaiseEvents to inform the Form that called the Shared method so that the form could update it's progress bar. However, if you try to RaiseEvent from a Shared method, you will get a compile error basically saying that you must have an instance object to use RaiseEvents.
So, I used Delegates instead, to accomplish a CallBack. This allows me to do the same things as RaiseEvent. The code for this article wil show you how to do this. You need to set up code in the calling form and in the Shared method of the class that is performing work for the form and periodically calling back to the form to allow it to display status.
The following code is placed in the calling Form. First, in the Declarations section of the form, I placed the Delegates as shown below:
| Public Delegate Sub ScanStart(ByVal piTotal As Integer) Public Delegate Sub ScanUpdate(ByVal piCurrItem As Integer) |
| Private Sub HandleScanStart(ByVal piTotal As Integer) Me.pbProgress.Value = 1 Me.pbProgress.Maximum = piTotal Me.pbProgress.Visible = True End Sub Private Sub HandleScanUpdate(ByVal piCurrItem As Integer) Me.pbProgress.Value = piCurrItem DoEvents() End Sub Private Sub HandleScanDone() Me.pbProgress.Visible = False End Sub |
| ' now show me so the progress bar will show Me.Show() DoEvents() Dim ss As ScanStart ss = AddressOf HandleScanStart Dim su As ScanUpdate su = AddressOf HandleScanUpdate Sessions.RefreshVariables(ss, su) Me.HandleScanDone() |
| Public Shared Function RefreshVariables( _ Optional ByVal ss As frmRefreshSessionVariables.ScanStart = Nothing, _ Optional ByVal su As frmRefreshSessionVariables.ScanUpdate = Nothing) _ As Boolean ' do some work to get the ProjectItems.Count ss.Invoke(prj.ProjectItems.Count) |
| If Not su Is Nothing Then piCurCount += 1 su.Invoke(piCurCount) End If |