Generic Windows Forms Controls

Today I discovered that the Windows Forms Designer in Visual Studio 2005 doesn’t know how to handle generics. For instance, the following example:

private class MyControl<T> : System.Windows.Forms.Control
{
}

could not be dropped in a Windows Forms designer (more on that in a little bit). If you go and decide to be a smart ass (like I usually am) and cheat the designer, you could drop a Panel (or any other control and manually edit the code in the InitializeComponent method and the Form.Designer.cs file to the class you want like so:

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new MyControl<int>();
// ...
}
#endregion
private MyControl<int> panel1;

This would throw the designer into a hissy fit:

 

The solution? Here are my suggestions for the VS Team:

  1. Dropping a generic control – My suggestion is that when a generic control is dropped, each type parameter will have a default value (can be decided on by using attributes, much like the DefaultValueAttribute) and will be editable in the property grid with a specialized designer.
  2. Having a generic control on a Form – It’s a bug and should be fixed. I know for certain that I am not the first person to come across this problem and that there is a workaround, but this is just annoying.
Advertisements

7 thoughts on “Generic Windows Forms Controls

  1. Hi,
    I cam across the problem and resolved it with reflection instead of a nice generic.
    I subscribe to the fact that generics controls have to be somewhat supported in the designer because they open a lot of opportunities.
    I hope for the next VS release.
    Cheers.

  2. This comment is to support Omer van Kloeten in his theory :), cause i faced the same problem, and to add that it wasn’t even supported in sp2 for visual studio 2005, come on VS Team ?!?!??!
    I’ll be trying this on the visual studio 2008, ill get back with a feedback.
    Cheers

  3. That would be so great! Imagine data binding a generic control with the type of the data bound element as parameter!
    It is the google search that got me here anyway. I’m sure some big head in MS will figure a way to do it someday… Just make it soon please! ;)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s