Karlovsky120
Karlovsky120

Reputation: 6352

Remove eventHandler that was added using lambda expression

I have a control that I added an event to. However, I needed to pass some extra parameters to the event method, so I use lambda expression like it was described here:

Pass parameter to EventHandler

comboBox.DropDown += (sender, e) => populateComboBox(sender, e, dataSource, selectedItem);

But this event should only fire the first time the conditions are met after what it should be removed.

Doing this doesn't work:

comboBox.DropDown -= (sender, e) => populateComboBox(sender, e, dataSource, selectedItem);

So the question is, is there a way to remove this method?

I've seen this:

How to remove all event handlers from a control

But I can't get it working for ComboBox DropDown event.

Upvotes: 4

Views: 3410

Answers (1)

vendettamit
vendettamit

Reputation: 14677

The problem that it's not getting removed is because you're giving a new lambda expression when removing it. You need to keep the reference of delegate created by Lambda expression to remove it from the control.

EventHandler handler = (x, y) => comboBox1_DropDown(x, y);
comboBox1.DropDown += handler;

It will work simply like:

comboBox1.DropDown -= handler;

via reflection:

    private void RemoveEvent(ComboBox b, EventHandler handler)
    {
        EventInfo f1 = typeof(ComboBox).GetEvent("DropDown");
        f1.RemoveEventHandler(b, handler);
    }

Upvotes: 3

Related Questions