bretddog
bretddog

Reputation: 5519

Inherit Form, no .Designer.cs

When I inherit from Form or a custom Form I don't always get a.Designer.cs file. If I then view the form and double-click it the InitializeComponent() method ends up in my derived class. How would I force a Designer.cs file to be created, and what may cause it not to be?

I see it does not happen to all my forms, but not sure what causes what..?

EDIT:

  1. create new project by right-click solution > Add > New Project > Windows Forms Application
  2. right click project > Add > Class > "FormA.cs"
  3. edit class: "public class FormA : Form" => still just seen as a class
  4. add method: public FormA(){} => Solution Explorer shows a form icon, but no sub-files
  5. Right click > View Designer => shows form
  6. Double click form => produce a FormA_Load method, and InitializeComponent method in FormA.cs, and produces a FormA.resx file. But no Designer.cs.

Upvotes: 3

Views: 3014

Answers (2)

Francesco Baruchelli
Francesco Baruchelli

Reputation: 7468

What's really happening here is that when you add a class or a form tou your VS project, it is created starting from a template. In fact, if you choose Add New Item instead of Add Class or Add Form, you can see both Class and Form among the list of all your installed templates (both the standard ones and the ones you can build on your own).

A template is simply an item where some names are parameterized (e.g. the class name and the namespace for the class). In the case of Form, the template is composed by two different files, whilst the class one contains just one file. The fact that there is the Designer file doesn't change the functionality of your class, it is simply a way of keeping the generated stuff out of your way so that you are less prone to modify it.

The fact that you view the form in the designer does not depend on the presence of the Designer file, but on the fact that Visual Studio, when you double click on your item looks for the DesignerAttribute of your class (which is inherited from Form), and decides how to open it.

Just try to quick view the result of this:

typeof(Form).GetCustomAttributes(typeof(DesignerAttribute), false);

Upvotes: 1

user743382
user743382

Reputation:

right click project > Add > Class > "FormA.cs"

That's the problem. The designer doesn't add .Designer.cs files. The designer uses the file that's already available.

If you create a new form, it will have a .Designer.cs file by default. You can then change the base class, and it will keep the .Designer.cs file.

If you create a new class, it will have no .Designer.cs file. The designer won't create one for you; it doesn't actually need it.

Upvotes: 4

Related Questions