tags:

views:

1552

answers:

3

I have 2 handlers using the same form. How do I remove the handlers before adding the new one (C#)?

+5  A: 

If you know what those handlers are, just remove them in the same way that you subscribed to them, except with -= instead of +=.

If you don't know what the handlers are, you can't remove them - the idea being that the event encapsulation prevents one interested party from clobbering the interests of another class in observing an event.

EDIT: I've been assuming that you're talking about an event implemented by a different class, e.g. a control. If your class "owns" the event, then just set the relevant variable to null.

Jon Skeet
+4  A: 

If you are working in the form itself, you should be able to do something like:

PseudoCode:

Delegate[] events = Form1.SomeEvent.GetInvokationList();

foreach (Delegate d in events)
{
     Form1.SomeEvent -= d;
}

From outside of the form, your SOL.

FlySwat
I've you've got access to the variable, just set it to null - no need to go through the invocation list...
Jon Skeet
A: 

I realize this question is rather old, but hopefully it will help someone out. You can unregister all the event handlers for any class with a little reflection.

public static void UnregisterAllEvents(object objectWithEvents)
{
    Type theType = objectWithEvents.GetType();

    //Even though the events are public, the FieldInfo associated with them is private
    foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
    {
        //eventInfo will be null if this is a normal field and not an event.
        System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name);
        if (eventInfo != null)
        {
            MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate;
            if (multicastDelegate != null)
            {
                foreach (Delegate _delegate in multicastDelegate.GetInvocationList())
                {
                    eventInfo.RemoveEventHandler(objectWithEvents, _delegate);
                }
            }
        }
    }
}
Greg B