0

I have the following custom Form (MyFrm) which inherits from Form.

public class MyFrm<T>: Form where T: class 
{
}

And following is my Form1:

 public partial class Form1: MyFrm<CONTACTS_BASE>
{

    public Form1()
    {
        InitializeComponent();
        MyInitialize();
    }

    public void MyInitialize()
    {
    }                     
}

as can be seen, there is nothing exceptional, However, when right click and select view designer I get the following error:

The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file: Form1 --- The base class 'MyGym.Controls.MyFrm' could not be loaded. Ensure the assembly has been referenced and that all projects have been built.

when I remove the part below and edit my Form1 accordingly I get no errors when I go to the designer mode. : Form where T: class

Why am I facing this issue? is there a fix for this? Thanks

Asım Gündüz
  • 1,257
  • 3
  • 17
  • 42
  • possible duplicate of https://stackoverflow.com/questions/13345551/why-do-base-windows-forms-form-class-with-generic-types-stop-the-designer-loadin – ashin Aug 05 '17 at 08:39
  • What version of VS are you using? I just tried basically the same thing you described in VS 2017 and it seems to have worked. If there was an issue with the designer in previous versions showing forms with generic base classes, it seems like they may have fixed it. – jmcilhinney Aug 05 '17 at 08:41
  • VS2013, I will try your fix =) thanks – Asım Gündüz Aug 05 '17 at 09:32
  • 1
    This is quite fundamental and can never work is intended. The rub is the way the Winforms designer works, it needs to create an instance of the base class of your form to provide the WYSIWYG design-time view. Problem is, it has no idea what type argument to use to create that instance. It will work fine in code, it can never work in the designer. – Hans Passant Aug 05 '17 at 11:19

1 Answers1

0

I believe you need to explicitly provide the InitializeComponent() method so that the Visual Studio IDE (Designer) works properly.

public class MyFrm<T> : Form 
    where T : class
{
    public MyFrm() : base()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {

    }
}

and then chain the constructors it together

public partial class Form1 : MyFrm<CONTACTS_BASE>
{
    public Form1() : base()
    {
        InitializeComponent();
        MyInitialize();
    }

    public void MyInitialize()
    {
    }
}

Note that : base was added to the constructor. However, in this example it's a bit overkill as the base constructor would already be called implicitly. I provided this addition, due to this answer. It states you must keep the constructor parameter-less in your base class.

Svek
  • 12,350
  • 6
  • 38
  • 69