How to “Unset” Event

前端 未结 5 1071
醉酒成梦
醉酒成梦 2021-01-19 15:10

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

相关标签:
5条回答
  • 2021-01-19 15:42

    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.

    0 讨论(0)
  • 2021-01-19 15:50

    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);
    
    0 讨论(0)
  • 2021-01-19 16:00

    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.

    0 讨论(0)
  • 2021-01-19 16:02
     //to subscribe
     comboboxname.Click += ComboboxClickHandler; 
    
     //to conditionally unsubscribe
     if( unsubscribeCondition)
     {
       comboboxname.Click -= ComboboxClickHandler;
     }
    
    0 讨论(0)
  • 2021-01-19 16:04

    Set:

    comboBox.Click += EventHandler;
    

    Unset:

    comboBox.Click -= EventHandler;
    
    0 讨论(0)
提交回复
热议问题