Nitin Kabra
Nitin Kabra

Reputation: 3226

How to remove all Event handler from a Control in C#.net

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 ?

Upvotes: 1

Views: 3122

Answers (3)

Rockstart
Rockstart

Reputation: 2377

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;
        }
    }

Upvotes: 0

BlackBear
BlackBear

Reputation: 22979

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.

Upvotes: 0

Sheridan Bulger
Sheridan Bulger

Reputation: 1214

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.

Upvotes: 1

Related Questions