By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,175 Members | 1,767 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,175 IT Pros & Developers. It's quick & easy.

Removing All Event Handlers

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.