Keith
Keith

Reputation: 155692

Can you use generic forms in C#?

You should be able to create a generic form:

public partial class MyGenericForm<T> :
    Form where T : class
{
    /* form code */
    public List<T> TypedList { get; set; }
}

Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource.

I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name.

Upvotes: 33

Views: 14906

Answers (4)

Nando
Nando

Reputation: 120

If paleolithic code doesn't affraid you

    public  static MyForm GetInstance<T>(T arg) where T : MyType
{
    MyForm myForm = new MyForm();

    myForm.InitializeStuffs<T>(arg);
    myForm.StartPosition = myForm.CenterParent;

    return myForm;
}

Use it

var myFormInstance = MyForm.GetInstance<T>(arg);                                                                      myFormInstance.ShowDialog(this);

Upvotes: 0

Ali Osman Yavuz
Ali Osman Yavuz

Reputation: 417

You can do it in three steps.

1) Replace in Form1.cs File

public partial class Form1<TEntity, TContext> : Formbase // where....

2) Replace in Form1.Designer.cs

 partial class Form1<TEntity, TContext>

3) Create new file : Form1.Generic.cs (for opening design)

partial class Form1
{
}    

Upvotes: 0

Matt Hamilton
Matt Hamilton

Reputation: 204169

Yes you can! Here's a blog post I made a while ago with the trick:

Designing Generic Forms

Edit: Looks like you're already doing it this way. This method works fine so I wouldn't consider it too hacky.

Upvotes: 22

Keith
Keith

Reputation: 155692

I have a hack to workaround this, which works but isn't ideal:

Add a new class to the project that inherits the form with its simple name.

internal class MyGenericForm:
    MyGenericForm<object> { }

This means that although the designer is still wrong the expected simple type (i.e without <>) is still found.

Upvotes: 0

Related Questions