Remove unused C# code in Visual Studio

11,243

Solution 1

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.

Solution 2

Here is another solution:

  1. Go to property (press F4), then go to an event.
  2. Select unwanted event, then right-click on event icon.
  3. Click 'Reset' to remove it from designer.cs automatically.
  4. Remove it in .cs file manually.
Share:
11,243
opt
Author by

opt

Updated on July 07, 2022

Comments

  • opt
    opt almost 2 years

    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?