0

At the beginning of a VB .NET function I remove an event handler and add it again at the end of the function because the function's code would trigger those events and I do not want them to trigger for the duration of the function. This usually works, but I have run into a few situations where the event still gets called even though I have already removed it. Sometimes removing it twice at the beginning of the function fixes it, but other times no matter how many times I remove it, it still fires. Any ideas on what could be causing this?

Edit

The code is in a Form that has a virtual mode datagridview. I want to run some operations that will trigger the CellValueNeeded event for the datagridview without that event being fired (because it will interfere).

Public Sub DoEventRaisingStuff()
    RemoveHandler grid.CellValueNeeded, AddressOf grid_CellValueNeeded

    'Do things that would trigger CellValueNeeded

    AddHandler grid.CellValueNeeded, AddressOf grid_CellValueNeeded
End Sub

Removing the handler multiple times does not prevent the event from firing, so it doesn't seem to be added multiple times somewhere else by accident.

Is there a way to find out what event handlers are active?

davidscolgan
  • 7,508
  • 9
  • 59
  • 78
  • If you post the code, it should be easier to help you out. – Dan Tao Jul 05 '10 at 20:14
  • That is true, but I don't really know what to post since I don't know where the problem is and the program is pretty large. I was more just wondering if anyone else has run into this problem before and what fixed it for them. – davidscolgan Jul 05 '10 at 20:23
  • You could at least post the code for the specific function you're talking about, though. – Dan Tao Jul 06 '10 at 03:24

2 Answers2

1

If the event handling code is being called then one of two things is happening:

  1. You aren't removing the event handler.

  2. You are adding the event handler multiple times. This is the more usual case.

In the past the only way I've been able to spot 2. is to find all the places where the event handler is added (hopefully only one or two) and put break points on those lines. I've then run the application under the debugger and found that it breaks more times than I expect. I use the call stack to work out why - it's always me putting the add code in the wrong place (on a button press rather than on form instantiation for example).

You can do the same with the removal code. Count the number of times each break point is hit and if they're not the same work back up the call stack to see if you can work out why.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
0

Use class scoped flag in the function and check the flag in the event handler.

i.e.:


Private RunFunction as Boolean = False

...

Private Sub MyEvent(e as system.eventargs) handles myObject.Method
   If RunFunction Then
      ...
   End If
End Sub

...

Private Sub MyFunction()
   RunFunction = False

   ...

   RunFunction = True
End Sub
Josaph
  • 429
  • 3
  • 7