ocespedes
ocespedes

Reputation: 1293

Can't remove event handler, adding multiple times

I have a piece of code where I add a handler everytime the form is open, I'm working in visual basic, but the first time I enter the form everything works fine, but for the second time I have 2 handlers, if I enter a third I have 3 handlers and so on. I don't know why is this happenning.

Here is what I tried so far.

I have stored all my machines in another class but I'm sending to myForm to show them, but to add them I use this code:

    Private Sub add_machine(ByRef machine As Machine)

    RemoveHandler machine.imgBox.Click, AddressOf Me.imgBox_Click
    AddHandler machine.imgBox.Click, AddressOf Me.imgBox_Click
    Me.Controls.Add(machine.get_imgMachine)

    Private Sub imgBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)        
    'Some code
    End Sub

Everytime I open the form I call the sub add_machine to add dinamically my machines, as you can see I send them ByRef to simplify my code I tried to put that RemoveHandler since I'm sending ByRef to avoid having more than one handler, but it's not working please help

Thanks in advance.

Upvotes: 0

Views: 379

Answers (1)

Steve
Steve

Reputation: 5545

Two things, DONT pass machine ByRef. You are not returning a new object. Please read this link for more information on when you should use what Byval vs ByRef

Second, add your handlers during form load (or initialization) and remove them in form closing. This will help ensure you are working with references to the same object.

Upvotes: 2

Related Questions