How to Delete an WinForms Control Event Handler Quickly

Recently a long-time user of Visual Studio looked over my shoulder when I deleted an event handler from my source code, and he said “uh, wait… how did you do that?”. If you are like him, not using the keyboard for this task, and would like to speed up things a bit, you may find this tip useful.

Imagine you have an event handler in a file MyForm.cs, e.g.

private void myButton_Click( object sender, EventArgs e )
{
   // ... some code ...
}

Deleting only this method obviously results in a compiler error as there’s a line

this.myButton.Click += new System.EventHandler( this.myButton_Click );

in the file MyForm.Designer.cs that has to be deleted as well.

To delete the event handler properly in Visual Studio 2005, using only the keyboard, perform the following steps:

  • In the MyForm.cs file, move the cursor on the name of the method file (i.e. myButton_Click) and press Shift-F12 (command Edit.FindAllReferences), which will bring you to the Find Symbols Results window.
  • press the Cursor Down key to move to the second line showing the occurrence of myButton_Click in the designer-generated code that connects the event with the handler method*
  • press Enter to jump to the MyForm.Designer.cs file
  • delete the current line by pressing Ctrl-Shift-L (command Edit.LineDelete)
  • jump back to the MyForm.cs by pressing Ctrl-Tab
  • and finally delete the code of the event handler method.

The description of the steps may sound a bit complicated at first, but you’ll find that the actual keystrokes come naturally pretty soon.

_____________
*) Note that this is only the case when the form was actually created in Visual Studio 2005 – keep your eyes open when working with forms in older projects that were started in Visual Studio .NET 200x.

5 Comments

Comments have been disabled for this content.