How can I easily duplicate a C#/VB Form in Visual Studio? If I copy & paste in the Solution Explorer, it uses the same class internally and gets messed up. How do you do it?
Just rename the class the designer references.
But a better solution is to create a new instance of the same class at run time.
Or better yet, create a parent form that various implementations inherit from.
I usually copy the files in windows explorer, open them up in Notepad/Wordpad and just change the one mention of the class name at the top. Include those files in your project, and you'll be good to go.
First of all, if you're duplicating a lot of forms with cut and paste, consider a common base class for your forms (or for a category of your forms) that implements shared/common functionality or look & feel elements. You can also create a template for new forms that meet your needs and create new forms from that template.
Personally I just cut and paste then fix any lingering name errors. Since I abstract out common functionality, I have not felt enough pain to look for a better way ;-)
- Copy and paste the form.
- Rename the pasted form .cs to match the new form class name. This should auto rename other related files.
- Open up .cs file. Change the class name and the name of the constructor(s) and destructor.
- Open up .Designer.cs file and change the class name.
Extra Credit:
- Consider abstracting common functionality from the form into common form or controls.
- Add a sub-folder to your project.
- Right-click on the sub-folder, and click Add Existing Item.
- Browse to the form you want to copy, and select its .cs file. This will duplicate the original form (partial and resx and all) in the sub-folder. The name will not conflict with the original, because the sub-folder will be included in its namespace.
- Right-click on the .cs file, click Refactor | Rename and enter the new name. This will also rename the partial and the resx for you.
I'm generally averse to methods of doing this that involve opening up the files in notepad or whatever, since I always think a common task like this should have a built-in way of doing it in Visual Studio. In this case, there is.