SmRndGuy
SmRndGuy

Reputation: 1819

How to remove the event handler after it had fired?

How to remove the event handler after the event handler had fired so that it can execute only once?

c.Click +=  (o,e)=>{
   Console.WriteLine("Clicked!");
   /*I want to remove this event handler now so that it doesn't fire anymore*/
}

Upvotes: 3

Views: 2865

Answers (2)

Tim S.
Tim S.

Reputation: 56536

This becomes easier if you use a named method instead of an anonymous lambda method.

c.Click += MyHandler;


void MyHandler(object sender, EventArgs e)
{
    Console.WriteLine("Clicked!");
    ((Button)sender).Click -= MyHandler;
}

Upvotes: 1

Servy
Servy

Reputation: 203821

You need to store the event handler in a variable, so that you can refer to it later. Because you want to refer to the handler from within the handler you also need to declare it before you initialize it. Finally, you cannot use an uninitialized variable, so you need to initialize it to null first, even though that null value will never be read from.

EventHandler handler = null;
handler = (o,e)=>{
   Console.WriteLine("Clicked!");
   c.Click -= handler;
}
c.Click += handler;

The other option would be to use a named method, rather than an anonymous method.

Upvotes: 7

Related Questions