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 ?

Nitin Kabra
  • 3,146
  • 10
  • 43
  • 62
  • 1
    Possible duplicate of: http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control – Dave Zych Oct 03 '12 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 ? – Nitin Kabra Oct 03 '12 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? – Andrew Barber Oct 03 '12 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. – Nitin Kabra Oct 03 '12 at 18:00
  • the method private void RemoveClickEvent(Button b) in this post http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control does the job, but it only removes the click event. – Nitin Kabra Oct 03 '12 at 18:03

3 Answers3

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.

Sheridan Bulger
  • 1,214
  • 7
  • 9
  • 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. – Nitin Kabra Oct 03 '12 at 17:53
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.

BlackBear
  • 22,411
  • 10
  • 48
  • 86
  • the method private void RemoveClickEvent(Button b) in this post http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control does the job, but it only removes the click event. – Nitin Kabra Oct 03 '12 at 18:02
  • @NitinKabra: Well, that's kind of an hacky way to get the job done ;) – BlackBear Oct 03 '12 at 18:08
  • Ah. Hacky reflection. I suppose it works, just substitute the event you want to use for `Click` – Sheridan Bulger Oct 03 '12 at 18:16
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;
        }
    }
Rockstart
  • 2,337
  • 5
  • 30
  • 59