WinForms: temporarily disable an event handler

Viewed 68444

How can I disable an event handler temporarily in WinForms?

5 Answers

Probably, the simplest way (which doesn't need unsubscribing or other stuff) is to declare a boolean value and check it at the beginning of the handler:

bool dontRunHandler;

void Handler(object sender, EventArgs e) {
   if (dontRunHandler) return;

   // handler body...
}

Disable from what perspective? If you want to remove a method that's in your scope from the list of delegates on the handler, you can just do..

object.Event -= new EventHandlerType(your_Method);

This will remove that method from the list of delegates, and you can reattach it later with

object.Event += new EventHandlerType(your_Method);

Disabling the event for the component. Pseudocode:

YourComponent.YourComponentEvent -= ExistingMethodForTheEvent;

Enabling

YourComponent.YourComponentEvent += ExistingMethodForTheEvent;

Example for events like CellFormatting in DataGridView:

//enabling
DataGridView1.CellFormatting += DataGridView1_CellFormatting;
//disabling
DataGridView1.CellFormatting -= DataGridView1_CellFormatting;

private void DgvBillings_CellFormatting(...) {
...
}

If you are using the just one event handler for a bunch of checkboxes or radio buttons you can also use something like:

var lSender = sender as RadioButton;
if (lSender?.Checked != true)
    return;
Related