How do I rename a form object (button, textbox, etc.) after Visual C# has autocreated the code?

9.8k Views Asked by At

Okay, so here's my problem: Whenever I create a button, textbox, listbox, then double-click to view the source code:

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

After this has been auto-created by Visual Studio, it won't allow me to change it later.

So when I go into properties and want to change "quitToolStripMenuItem" (in the Name property field) to "mnuQuit," it will show up in the properties window properly, and will change the name (for all intents and purposes), but when I double-click to view source - it still shows the 'quitToolStrip..." name.

If I rename it to

private void mnuQuit_Click(object sender, EventArgs e)

It will throw a big hissy fit, and then my form design will be gone and a (basically) 404 message will appear instead of the form.

How can I do it without deleting the item and then recreating?

3

There are 3 best solutions below

1
On BEST ANSWER

If you want to rename the event handler method, go to the designer, select the object (the menu item in your case), and in the properties window click the events button (it looks like a lightning bolt), and rename the event handler method from there.

In C#, the event handler is linked to the object that raise the event by a delegate, so the name of the method does not matter. You can have a button called Jack and event handler called Jill_Click that will actually handle the resize event of Jack. If you open the designer code you will see something like:

this.Jack.Resize += new System.EventHandler(this.Jill_Click);
2
On

Just refactor the method name? This will update it on the .designer.cs, in your designer and of course in your code.

Select the method name, right click, RefactorRename.

1
On

Click on the Events (lightning) icon at the top of the Properties window and delete the text in the Click field.