1

I am using some recursive function during my form load. I am attaching event handlers on controls programmatically. Due to recursive function, event handlers get hooked multiple times to a control. I want to remove all handlers from these controls.

Eg. I have added keypress, keydown, gotfocus etc. events in a textbox. I want to remove all these handlers. How do achieve it ?

5
  • 1
    Possible duplicate of: stackoverflow.com/questions/91778/… Commented Oct 3, 2012 at 17:49
  • well it removes only the click event. I want to remove all the events from a control. How do I do it ? Commented Oct 3, 2012 at 17:51
  • 1
    It sounds like the multiple handlers was not intended... Wouldn't it be better to just keep from adding multiple handlers in the first place? Commented Oct 3, 2012 at 17:57
  • I want to add it once, not more than that. i.e. keypress, keydown, gotfocus all these once. but due to some function calls these are getting added more than once. Commented Oct 3, 2012 at 18:00
  • the method private void RemoveClickEvent(Button b) in this post stackoverflow.com/questions/91778/… does the job, but it only removes the click event. Commented Oct 3, 2012 at 18:03

3 Answers 3

1

if loEventHandler is an event handler you've previously subscribed to an event (Click, for example), you can remove it by doing loBox.Click -= loEventHandler;.

Events can also be cleared within the private scope by setting the event to null MyEvent = null; That doesn't work for the public scope, though.

Sign up to request clarification or add additional context in comments.

1 Comment

I am looking to remove all events. It can be messy if I add more handlers, more than 5,6. so I want to remove all at once.
0

You can't do it from the "outside" world since events are special kinds of delegates which don't allow subscribers to interfere between each other.

3 Comments

the method private void RemoveClickEvent(Button b) in this post stackoverflow.com/questions/91778/… does the job, but it only removes the click event.
@NitinKabra: Well, that's kind of an hacky way to get the job done ;)
Ah. Hacky reflection. I suppose it works, just substitute the event you want to use for Click
0

To avoid a single event being registered multiple times , you can add a property wrapper like this

    public event EventHandler<EventArgs> _event;
    public event EventHandler<EventArgs> PublicEvent
    {

        add
        {
            if (_event == null)
                _event += value;
        }

        remove
        {
            _event -= value;
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.