R. Salehi
R. Salehi

Reputation: 183

Raise an event on another form

I have two separated form(usercontrol A & B) in VB.Net. When a button clicked on formB, I want to an event raised on formA. How can do that? I searched stackoverflow.com and check several related solutions but they didn't work for me. I don't know what is the problem! Please help me. For Example I tried this code:

FormA:

Dim MyEditForm As New ucEmployeeTimeEdit
'some code for showing and preparing MyEditForm 
Private Sub GetSomeClick() Handles MyEditForm.MyClick
    System.Console.WriteLine("test")
End Sub

FormB:

Public Event MyClick()
Private Sub BtnDelet_Click(sender As Object, e As EventArgs) Handles btnDelet.Click
    RaiseEvent MyClick()
End Sub

Upvotes: 0

Views: 1812

Answers (2)

laancelot
laancelot

Reputation: 3207

While Idle_Mind answer is great, here's an alternative method with different advantages. (EDIT: I just noticed that he mentions this too, so you can consider this an elaboration on this subject)

If you keep FormB as a modal variable inside FormA, you can tell VB that you want to use it's events. Here's some skeleton code to show you:

Public Class FormA
    Private WithEvents myFormB As FormB

    'rest of the code for FormA
    'you can use FormB's events like this

    Private Sub GetSomeClicks() Handles myFormB.MyClick
        'code code code
    End Sub
End Class

Public Class FormB
    Public Event MyClick()
End Class

Have fun!

Upvotes: 3

Idle_Mind
Idle_Mind

Reputation: 39152

Somewhere in the some code portion, you need to use AddHandler to "wire up" that event:

Public Sub Foo()
    Dim MyEditForm As New ucEmployeeTimeEdit
    'some code for showing and preparing MyEditForm 
    AddHandler MyEditForm.MyClick, AddressOf GetSomeClick
End Sub

Private Sub GetSomeClick()
    System.Console.WriteLine("test")
End Sub

Note that GetSomeClick() does not have a "Handles" clause on the end. This is because your instance of ucEmployeeTimeEdit was a local variable.

If you had declared it as WithEvents at class level, then you could use the "Handles" clause (and consequently would no longer need the AddHandler call).

Upvotes: 3

Related Questions