How to “Unset” Event

2020-04-08 15:28发布

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.

标签: c# .net events
5条回答
Luminary・发光体
2楼-- · 2020-04-08 15:58

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);
查看更多
家丑人穷心不美
3楼-- · 2020-04-08 16:06

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.

查看更多
干净又极端
4楼-- · 2020-04-08 16:06

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.

查看更多
beautiful°
5楼-- · 2020-04-08 16:09

Set:

comboBox.Click += EventHandler;

Unset:

comboBox.Click -= EventHandler;
查看更多
我想做一个坏孩纸
6楼-- · 2020-04-08 16:09
 //to subscribe
 comboboxname.Click += ComboboxClickHandler; 

 //to conditionally unsubscribe
 if( unsubscribeCondition)
 {
   comboboxname.Click -= ComboboxClickHandler;
 }
查看更多
登录 后发表回答