Handle event of a User Control's control in a

2019-05-14 19:44发布

问题:

I have a Button in UserControl1. I am using UserControl1 in Form1. I want to handle Button's Click event in Form1.

I tried to do same via:

AddHandler userControl1.Button1.Click, AddressOf Button1_Click

And:

Public Sub Button1_Click(ByVal sender As Object, ByVal args As EventArgs) Handles userControl1.Button1.Click

End Sub

but getting error.

回答1:

Create your event on the UserControl:

Public Class UserControl1

    Public Event UC_Button1Click()

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        RaiseEvent UC_Button1Click()
    End Sub

End Class

And then use the new event:

AddHandler userControl1.UC_Button1Click, AddressOf Button1_Click

Or you can simply define it like this on the UserControl and access to it from outside (not recommended):

Public WithEvents Button1 As System.Windows.Forms.Button

And then:

AddHandler uc.Button1.Click, AddressOf Button1_Click