Winforms - Visually remove button click event

耗尽温柔 提交于 2019-12-18 03:09:12

问题


.NET newbie alert

Using Visual C# 2008 Express Edition I have accidentally created a click event for a button. I then deleted the automatically-created method code, which resulted in an error saying that the function, which had now been referenced in the form loading code, could no longer be found.

Deleting the following line from the Form1.Designer.cs file's InitializeComponent() function...

this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click);

... seems to do the trick, however, it makes me feel very dirty because of the following warning at the beginning of the #region:

/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.

I haven't been able to find a way to do this using the form designer, which I assume is the means implied by this warning. What is the correct way to do this?


回答1:


You do have to be careful when working in the designer.cs files but you don't have to feel dirty about it (when I make the same mistake it is just easier to fix it the designer.cs file). You can do it visually like this:

  1. Open the form in the form designer.
  2. In the form designer, click the button of interest.
  3. Press F4 (or right click the button and then click properties). The properties pane should show up.
  4. At the top of the properties pane, click the lightning bolt. This shows the events for the button.
  5. Find the click event and clear its handler.



回答2:


Okay, I am usually the one advocating the use of notepad2 or some other text editor to perform coding tasks.

But, since you ask how to do so in the Designer...

  1. Open the form where the erroneous event was added to a control.
  2. Select the control.
  3. Right-click, select "Properties".
  4. Change to "Events" by selecting the button with the lighting-bolt icon.
  5. Select the event you need to remove.
  6. After placing the mouse in the box which is showing the event handler method name, delete all of the text in that box and press enter. This will remove the event handler and the delegate assignment for this event on your control.

The only caveat being: if you wish to preserve your event handler method (i.e. it is not auto-generated by Visual Studio) - you probably want to avoid deleting the assignment in this manner. Because when I say that it removes the event handler - I should say that the declaration of the event handler method in "Form1.cs" (for example) will be deleted as well.



来源:https://stackoverflow.com/questions/2751782/winforms-visually-remove-button-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!