Check if a specific event handler method already attached
Late answer here. I believe Parimal Raj answer is correct, as I could not find a way to directly access the events. However, here are two methods I created to get around this:
Delete before adding. If the method isn't there, I did not receive an error trying to delete the nonexistant method. This way you can insure the invocation list calls method1 only once.
Event -= MyMethod1; Event += MyMethod1;
The objects you are adding an event to may have a .Tag property. You can use the Tag to store info about the methods you already added. Here I only have one method, so I just need to check if Tag is null. But more complicated scenarios can be handled this way:
if(control.Tag == null) { //ony added once, when tag is null control.TextChanged += new EventHandler(validate); control.Tag = new ControlTag(); }
foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
{
if ( existingHandler == prospectiveHandler )
{
return true;
}
}
loop through the delegates using the GetInvocationList
method.
Event.GetInvocationList().Any(x => x.Method.Name.Equals("yourmethodname"));
No. You cannot.
The event keyword was explicitly invented to prevent you from doing what you want to do. It makes the delegate object for the event inaccessible so nobody can mess with the events handlers.
Source : How to dermine if an event is already subscribed