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.
+13
A:
Set:
comboBox.Click += EventHandler;
Unset:
comboBox.Click -= EventHandler;
maciejkow
2009-07-24 16:28:34
+1
A:
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.
Tamás Szelei
2009-07-24 16:29:10
A:
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);
JeffH
2009-07-24 16:29:20
+1
A:
//to subscribe
comboboxname.Click += ComboboxClickHandler;
//to conditionally unsubscribe
if( unsubscribeCondition)
{
comboboxname.Click -= ComboboxClickHandler;
}
Mehmet Aras
2009-07-24 16:32:56
you have to remove the reference to the eventhandler, as Mehmet has here. If you just do:what JeffH is suggesting, it won't actually result in the handler being removed.
Irwin
2009-07-24 16:35:45
Irwin - can you elaborate? I tried my example and my "-=" line does indeed cause the event handler to no longer be called.
JeffH
2009-07-24 17:34:52
in you answer Jeff -= new EventHandler() will only work if that new instance is equal to some instance in the invocation list for the event when using -= you should keep around a reference to the handler you want to remove
SpaceghostAli
2009-07-24 17:44:01
I understand that keeping a reference is the correct way to do this. I'm still confused about what's happening in the code I posted - it works in a toy app I just built in VS2005. Has behavior changed since then?
JeffH
2009-07-24 18:30:55
I no longer think keeping a reference is necessary or correct. Not only does it work for me the way my answer shows, the discussion on this thread http://stackoverflow.com/questions/1341895/c-event-removal-syntax suggests that remove doesn't compare for instance equality but equality of target and method signature.
JeffH
2009-08-27 17:10:10
+2
A:
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.
Martin Liversage
2009-07-24 16:39:16