Generic ComboBox in a Windows Forms Application

I need to have a class derived from ComboBox that will only accept objects of a specific type. So, I need to have a generic ComboBox. If I declare a new class as follows:

public class GComboBox <Type> : ComboBox { // Some code } 

then GComboBox will not appear in the Windows Form toolbar. How to make it appear in the toolbar so that I can put it there, since I could put any other derivative not common ComboBox?

+1
source share
2 answers

The easiest way to use this GComboBox is as follows:

  • use ComboBox instead of GComboBox , then go to Form1.Designer.cs and replace GComboBox with ComboBox .

if you want to explicitly drag the toolbar, you need to create a Class Library (from the new Visual Studio project studio) and add it to the toolbar Adding custom control DLLs to the Visual Studio ToolBox

0
source

Instead of a general control, you can use a regular subclass with Property:

  public class GComboBox : ComboBox { public Type myType { get; set; } public GComboBox(Type type) { myType = type; } public GComboBox() { myType = typeof(int); } public override string ToString() { return "GComboBox<" + myType.ToString() + ">"; } } 

This will appear in the toolbar as expected. By default, it is equal to System.Int32 , which you must adapt after placing it, for example. in the form constructor.

  InitializeComponent(); gComboBox1.myType = typeof(Bitmap); 

Not sure how you could prevent the addition of the wrong types, though .. There is no ItemAdded event. This post suggests listening to ComboBox posts, but most posts tell you that you still control the addition of items.

0
source

All Articles