How to "Unset" Event

If I have a combobox click event set in the designer.cs page and then at some point during the running of the program, based on some condition, I no longer want the combobox Click event to be set, how do I "unset" it? I've tried comboboxname.Click += null and I've tried setting it to another dummy function that does nothing...neither works.

Upvotes: 4

Views: 861

Answers (5)

Martin Liversage
Martin Liversage

Reputation: 106836

The reason you cannot use

comboboxname.Click = null

or

comboboxname.Click += null

is that the event Click actually contains a list of event handlers. There may be multiple subscribers to your event and to undo subscribing to an event you have to remove only your own event handler. As it has been pointed out here you use the -= operator to do that.

Upvotes: 2

Mehmet Aras
Mehmet Aras

Reputation: 5374

 //to subscribe
 comboboxname.Click += ComboboxClickHandler; 

 //to conditionally unsubscribe
 if( unsubscribeCondition)
 {
   comboboxname.Click -= ComboboxClickHandler;
 }

Upvotes: 1

JeffH
JeffH

Reputation: 10482

Assuming your handler is assigned like this:

this.comboBox1_Click += new System.EventHandler(this.comboBox1_Click);

disable it like this:

this.comboBox1.Click -= new System.EventHandler(this.comboBox1_Click);

Upvotes: 0

Tamás Szelei
Tamás Szelei

Reputation: 23941

Use the -= operator.

this.MyEvent -= MyEventHandler;

Your question indicates you don't have a good understanding of events in c# - I suggest looking deeper into it.

Upvotes: 1

maciejkow
maciejkow

Reputation: 6453

Set:

comboBox.Click += EventHandler;

Unset:

comboBox.Click -= EventHandler;

Upvotes: 13

Related Questions