views:

55

answers:

2

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?

A: 

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
+1  A: 

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