Remove unused C# code in Visual Studio

opt picture opt · Oct 4, 2014 · Viewed 9.8k times · Source

when working on a windows form I have accidently clicked on buttons and now I have part of code related to this click event. I don't need them and I would like to remove these parts from the code but, if I do, Visual Studio complains when compiling cause it search for that missing code. How can I get rid of unused click events on my code?

Answer

TyCobb picture TyCobb · Oct 4, 2014

When you double-click on a control, the default event gets wired up and a stubbed out handler gets created for you.

The stubbed handler you know about as you saw it and deleted.

private void button1_Click(object sender, EventArgs e)
{
}

The other piece is where the event actually gets wired. This is where the compile error comes from. You deleted the event handler, but did not remove the event subscription.

This can be found in the Designer.cs file attached to the specific form.

private void InitializeComponent()
{
    this.button1 = new System.Windows.Forms.Button();
    this.SuspendLayout();
    // 
    // button1
    // 
    this.button1.Name = "button1";

    //This is the line that has the compile error.
    this.button1.Click += new System.EventHandler(this.button1_Click);
}

As mentioned in the comments, you can go to the event properties for that control and reset the event, but you can also go into the designer and remove the invalid line. Using the Reset command will remove the stub and the event subscription.