3

I need to create a custom User Control with generics because I have a BindingSource with a data source of type T

public partial class ABMControl<T> : UserControl
{
    public ABMControl()
    {
        InitializeComponent();
        this.bindingSource.Datasource = typeof(T);
    }
}

In the form designer the custom user control does not appear in toolbox because is generic. What is the solution?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Federico Fia Sare
  • 1,166
  • 2
  • 8
  • 15
  • Possible duplicate of [Generic base class for WinForm UserControl](https://stackoverflow.com/questions/677609/generic-base-class-for-winform-usercontrol) – TnTinMn Mar 24 '18 at 16:31
  • When dropping a control from toolbox, you are commanding the designer to create an instance of that control. You cannot create an instance of `GenericControl`. Instead you need an instance of `GenericControl`. So it completely makes sense why the generic control doesn't appear in toolbox because it has no usage in designer. – Reza Aghaei Mar 25 '18 at 01:37
  • Also starting from VS2015.1, designer shows classes which have generic base classes without any problem. So the workaround which is linked in the first comment is no more required for newer versions of VS. – Reza Aghaei Mar 25 '18 at 09:51

1 Answers1

6

It's expected behavior for toolbox.

When dropping a control from toolbox onto your form, you are commanding the designer to create an instance of that control. You cannot create an instance of GenericControl<T> without determining T. Instead you need an instance of GenericControl<SomeClass>.

So it completely makes sense the generic control doesn't appear in toolbox because it has no usage in designer and designer doesn't know what type should it use for generic parameter when creating instance.

Also about designer, considering this post: Generic Base Class for UserControl starting from VS2015.1, Windows Forms Designer shows classes which have generic base classes without any problem. The following class will be shown in designer without any problem:

public class SomeClassControl:GenericControl<SomeClass>
{
}

For older versions of Visual Studio, use the workaround which is described in the linked post:

public class SomeClassControl:SomeClassControlBase
{
}
public class SomeClassControlBase:GenericControl<SomeClass>{}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398