4

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.

Community
  • 1
  • 1
Karlovsky120
  • 6,212
  • 8
  • 41
  • 94
  • Possible duplicate of [Unsubscribe anonymous method in C#](http://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c-sharp) – devuxer Mar 15 '16 at 21:22
  • Also possible duplicate http://stackoverflow.com/questions/1362204/how-to-remove-a-lambda-event-handler. – devuxer Mar 15 '16 at 21:23

1 Answers1

3

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);
    }
vendettamit
  • 14,315
  • 2
  • 32
  • 54
  • That doesn't work because I need to remove the eventHandler from within itself, and this won't take itself as a parameter, since it's still unassigned. I could create a chain of events, but that is getting more complicated than I would like. – Karlovsky120 Mar 15 '16 at 21:31
  • 1
    Why not keep the handler as class member or may be in named cache? Remove it when your conditions are met by accessing it as member or cached reference. – vendettamit Mar 15 '16 at 21:35
  • Fixed it. Created a handler beforehand with a dummy method, then wrote what you did there. – Karlovsky120 Mar 15 '16 at 21:37