3

I have a scenario in which I have to implement a UserControl , On Clicking a button "Process" a background worker works.

I want to trigger a Function/Method of my parent form where I am going to add that UserControl upon "RunWorkerCompleted" Event.

Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
    Try            
        bgwFetchGiftCard.RunWorkerAsync()
    Catch ex As Exception
        WriteLog(ex)
    End Try
End Sub

Private Sub bgwFetchCard_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwFetchCard.DoWork
    Try
        ds = New DataSet()
        'Call ApI Service for Denomination
        ds = APICALL()
    Catch ex As Exception
        WriteLog(ex)
    End Try
End Sub

Private Sub bgwFetchCard_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwFetchCard.RunWorkerCompleted
    If ds IsNot Nothing Then
        Result = True   
        'At This Point I Want To Raise Event          
        'RaiseEvent 
    Else
        'ShowMessage("FAIL")
    End If
End Sub

How may i achieve this?anybody kindly suggest

DareDevil
  • 5,249
  • 6
  • 50
  • 88
  • 1
    Add a `Public Event` declaration to your code, raise that one. Hiding worker threads in a user control is not a fantastic idea. You'll need to think about what's going to happen when the user closes the Form on which this control lives and the worker is still running. You can't [use this](http://stackoverflow.com/a/1732361/17034). – Hans Passant Jul 27 '15 at 13:36

1 Answers1

3

Assuming the code shown is in the UserControl, you just need to declare an event and raise it (there is nothing special to this regarding a UserControl):

Public Event SomethingIsDone (sender As Object, e as EventArgs)

...
Private Sub bgwFetchCard_RunWorkerCompleted(sender As Object, 
          e As RunWorkerCompletedEventArgs) Handles bgwFetchCard.RunWorkerCompleted
    If ds IsNot Nothing Then
        Result = True   

         RaiseEvent SomethingIsDone(Me, New EventsArgs()) 

    Else
        'ShowMessage("FAIL")
    End If
End Sub

In cases where you need to pass information in the event, define a custom EventArgs class which inherits from EventArgs add the properties you need:

Public Class SomethingDoneEventArgs
    Inherits EventArgs

    Public Property SomethingName As String

    ' convenience:
    Public Sub New(name As String)
        SomethingName = name
    End Sub
End Class

Then pass an instance of that class rather than the the generic EventArgs:

...
RaiseEvent SomethingIsDone(Me, 
           New SomethingDoneEventArgs("foo")) 
Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178