Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if an event has been attached to yet

I have two objects - one that contains some code with will fire an event, and one that contains the handler for that event. I can't "AddHandler" in the Load of the first object, because an instance of the second object doesn't exist yet. When I raise my event, I want to check to see if a copy of object2 has been instantiated (easy to do), and if a handler has been attached to the event yet (not sure how to do this).

I'm also open to another recommendation about how to do this instead. If I do my AddHandler in Object1.Load, and Object2 doesn't exist yet, then it will never handle my event, even if I create it later. Right now, in the code that fires the event, I've just resorted to doing a RemoveHandler and then an AddHandler every single time the event is raised, and then I know I'll attach when the object finally exists, but I know this is a crappy method.

I saw an article about something similar (Determine list of event handlers bound to event), and maybe I'm missing something in the translation, but I can't get the code to work on my custom event in VB.NET.

like image 655
SqlRyan Avatar asked Jun 18 '09 14:06

SqlRyan


2 Answers

You could also just have a bool field that you check before hooking the event.

if not eventHooked then
 addhandler
 eventHooked = true
end if

Also if you need a good c# to vb converter http://www.tangiblesoftwaresolutions.com/ has one that can translate a 100 lines on the fly or less for or translate a project of a 1000 lines for free. More than that you have to purchase it, but that usually those limits will work just fine. No I am not trying to advertise for them :-)

like image 141
NastyNateDoggy Avatar answered Sep 30 '22 12:09

NastyNateDoggy


VB.Net creates a special private member variable in the pattern of <YourEvent>Event that you can then use to test against Nothing.

Public Event MyClick As EventHandler

Private Sub OnMyClick()
    If MyClickEvent IsNot Nothing Then
        RaiseEvent MyClick(Me, New EventArgs())
    Else
        ' No event handler has been set.
        MsgBox("There is no event handler. That makes me sad.")
    End If
End Sub

http://blogs.msdn.com/b/vbteam/archive/2009/09/25/testing-events-for-nothing-null-doug-rothaus.aspx

like image 36
Jon Avatar answered Sep 30 '22 12:09

Jon