Removing All Event Handlers

M

MuZZy

Hi,

Is there a way to remove all event handlers for a control's event? Say, i have a button and i want
to remove all button.Click events for it - i don't know how many of them was hooked to the event and
what are the functions hooked, but i need to make sure that i unwired all of them at once.

I could unwire event handlers if i knew the functions:

button.Click += new EventHandler(OnMyBtnClick); // Wire event handler
....
button.Click -= new EventHandler(OnMyBtnClick); // Unwire event handler

But again, i don't know which/how many event handlers are wired to the event.


Any ideas/comments would be highly appreciated!

Thank you
Andrey
 
G

Guest

Directly no, in large part because you cannot simply set the event to null.

Indirectly, you could make the actual event private and create a property
around it that tracks all of the delegates being added/subtracted to it.

Take the following:

ArrayList delegates = new ArrayList();

private event EventHandler MyRealEvent;

public event EventHandler MyEvent
{
add
{
MyRealEvent += value;
delegates.Add(value);
}

remove
{
MyRealEvent -= value;
delegates.Remove(value);
}
}

public void RemoveAllEvents()
{
foreach(EventHandler eh in delegates)
{
MyRealEvent -= eh;
}
delegates.Clear();
}

In this code, we create a wrapper around MyRealEvent (which is what you
would actually trigger internally), so that anytime something is
added/subtracted to it, a list of those EventHandlers is updated accordingly.
When you finally need to clear out all of the events, simply call
RemoveAllEvents() (poorly named I know) which iterates through the list of
EventHandlers and removes each in turn from the real event.

Brendan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top