在VB.NET自定义控件中添加事件处理程序

时间:2015-07-27 13:25:04

标签: vb.net winforms events user-controls

我有一个场景,我必须实现一个UserControl,On Clicking按钮“Process”后台工作者可以工作。

我想触发父表单的函数/方法,我将在“RunWorkerCompleted”事件上添加UserControl。

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

我怎么能实现这个目标?任何人都建议

1 个答案:

答案 0 :(得分:2)

假设显示的代码位于UserControl中,您只需要声明一个事件并将其引发(对于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

如果您需要在事件中传递信息,请定义一个继承自EventArgs的自定义EventArgs类,添加您需要的属性:

Public Class SomethingDoneEventArgs
    Inherits EventArgs

    Public Property SomethingName As String

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

然后传递该类的实例而不是通用的EventArgs

...
RaiseEvent SomethingIsDone(Me, 
           New SomethingDoneEventArgs("foo"))