I am starting to try and create windows forms using C# in Visual Studio 2008.

I added a button to my form, and when I clicked it, the event handler code was generated as expected:

private void button1_Click(object sender, EventArgs e)

The book I am following also says that when I delete a control from the form, the code for it will also be deleted, but when I right click on the button and select Delete, the event handler code is still there. The button however has gone from the form.

I tried to rebuild my project thinking it might then remove the the event handler code, but is was still there.

So basically I was wondering how you delete a form component, and have visual studio also remove the code for it, which it added in the first place.

Thanks for any help!!


Short answer: Visual Studio deletes all code used to create that button and display it on the form, but doesn't delete any functions assigned to its events.

Long answer: There are several benefits of Visual Studio not deleting the event functions for a control. One is if you wanted to create another control that used the same logic, you still had your old code (maybe you are replacing an "Apply" button with "OnKeyDown" event handler of a textbox.) A more obscure benefit (because it isn't used so often) is you can have multiple controls execute the same function. For example, if you have an "OK", "Apply" and "Cancel" button on your form, you can tell the "OK" and "Apply" buttons to call the exact same function (that function can check which button was clicked, and close the dialog if it was the "OK" button.) If you delete the Apply button, you don't want your function deleted, because the OK button still uses it.

Note: You can delete the function itself if you don't want it anymore, there is no other tricks or gotchas to worry about

Edited 7 Years Ago by mikiurban: Added note

delete not deleting,, deleted a button
Private Sub Button52_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
and the code is still there,,

its just abutton, not linked to anything,

why doesnt visual studio delete the code too?

and,, is there some way to delete a bunch of buttons then delete the code
after without having to search for the old buttons that i dont now know
which ones are which?

This article has been dead for over six months. Start a new discussion instead.