469,280 Members | 2,045 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,280 developers. It's quick & easy.

Removing All Event Handlers

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
Nov 17 '05 #1
1 48445
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
"MuZZy" wrote:
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

Nov 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

13 posts views Thread by Charles Law | last post: by
14 posts views Thread by Hamed | last post: by
1 post views Thread by Armin Zingler | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.