views:

794

answers:

6

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?

A: 

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.

Neil N
+1  A: 

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.

JamesMLV
Thank you. This is the most practical since I have no "Base Class" functionality, only little "template" like features customized that I won't like to do again manually.
Jenko
C#/VB.NET let you inherit forms just like any other class, so if you have just a common template...
R. Bemrose
+1  A: 

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 ;-)

Eric J.
+1  A: 

Inherit the form!

Jon
I +1'd this purely on the basis that it is the best solution. Is this correct? It would work fine surely?
Finglas
yep, have a base form and everything on the base form would appear in the form that inherited it.
Jon
+1  A: 
  1. Copy and paste the form.
  2. Rename the pasted form .cs to match the new form class name. This should auto rename other related files.
  3. Open up .cs file. Change the class name and the name of the constructor(s) and destructor.
  4. Open up .Designer.cs file and change the class name.

Extra Credit:

  1. Consider abstracting common functionality from the form into common form or controls.
Michael McCloskey
A: 
  1. Add a sub-folder to your project.
  2. Right-click on the sub-folder, and click Add Existing Item.
  3. 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.
  4. 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.

MusiGenesis