I've written some code to handle an event as follows:
AddHandler myObject.myEvent, AddressOf myFunction
It seemed that everything was working at first, but when I ran the debugger, I discovered that oftentimes, myFunction
would run several times each time myObject.myEvent
fired. I figured out that I had allowed the code to add the event handler to run more than once, resulting in this behavior.
Is there a way I can do something like this?
If myObject.myEvent is not handled Then
AddHandler myObject.myEvent, AddressOf myFunction
End If
If you are looking to see if a specific handler (function) has been added then you can use array. You can examine various properties on the Method property of the delegate to see if a specific function has been added. If you are looking to see if there is just one attached, you can just test for null.
Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence like system generated notifications. Applications need to respond to events when they occur. Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples of events.
In C#, an event is connected to its handler by an event delegate. To raise an event and respond to the event, the two necessary elements are the delegate that links the event to its handler method and the class that holds event data.
Event Handling Using ControlsAll ASP.NET controls are implemented as classes, and they have events which are fired when a user performs a certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling events, there are in-built attributes and event handlers.
Remove the handler and then add it. This way it will never be duplicated. Beware of the null reference error if your object does not exist. I got caught on that too and may happen when you are removing the handler outside the sub where the handler is created.
if not myObject is nothing then RemoveHandler myObject.myEvent, AddressOf myFunction
if not myObject is nothing then AddHandler myObject.myEvent, AddressOf myFunction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With