0

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.

3
  • Is machine passed to this function is the same as in previous call? If not, this will not work. You need to unsubscribe from previous machine instance.
    – Alex F
    Sep 21, 2014 at 13:10
  • I think is the same machine because I have a button that calls this form, my main form is always open and that is where I store the machines, how would I know if is not the same instance.
    – ocespedes
    Sep 21, 2014 at 13:41
  • You tagged this as VBA, but maybe you mean Visual Basic? Have you taken a look at: msdn.microsoft.com/en-us/library/6yyk8z93(v=vs.90).aspx Sep 21, 2014 at 15:22

1 Answer 1

2

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.

1
  • I didn't think in that way, I feel so stupid right now thanks
    – ocespedes
    Sep 22, 2014 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.