简体   繁体   中英

C# How to properly remove event handler code?

I have a keyup event that I want to remove from my C# Winform:

private void txtInputBox_KeyDown(object sender, KeyEventArgs e)
{
      if (e.KeyCode == Keys.Return)
      {
          cmdSend.PerformClick();
      }
  }

If I comment out or delete this function I get an error in the design view of the form:

"The designer cannot process unknown name 'txtInputBox_KeyDown' at line 66. The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again."

The program also will not compile.

It happens if I try to delete any event handler code on my form. I am teaching myself C# from my background in VB.NET and in VB.NET I could remove event handler code without issue.

It is because in Designer.cs event handler is registered and when you just delete from code behind it's method, it does not remove it's event registration from Designer.cs

you should remove event from form designer view by going in control properties so that this issue not comes or from Designer.cs remove event registration line which will be like:

SomeTextBox.KeyUp += SomeTextBox_KeyUp

thats because in C#, the functions are added to the events programatically by the designer, when you add it in the designer.

In the solution explorer window, Expand Form1.cs and open the Form1.Designer.cs file there:

在此处输入图片说明

then locate the function :

private void InitializeComponent()

and delete the line that registers your event handler to the event. it will have a += operator in the middle like this:

在此处输入图片说明

your event will be located at line 66 and will look like this:

this.txtInputBox.KeyDown += new System.EventHandler(this.txtInputBox_KeyDown);

In the designer code that is automatically generated by Visual Studio the event is still linked to this non-existent function.

In the Solution Explorer, find your Form.Designer.cs file (it is in a subnode under the main Form.cs), or use the Find in Solution function to find the line that says

txtInputBox.KeyDown += new System.EventHandler(txtInputBox_KeyDown);

Delete the line, and it should work again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM