1

I need to have a class derived from ComboBox that will only accept Objects of some specific type. So, I need to have a generic ComboBox. If I declare a new class like this:

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

then GComboBox will not appear in the toolbox of Windows Form. How do I make it appear in the toolbox so that I can put it there as I would be able to put any other derived non-generic ComboBox?

user3623874
  • 520
  • 1
  • 6
  • 25
  • Why you need it to be shown in the ToolBox go in the designer of the page and add it manually. – mybirthname Sep 14 '14 at 11:18
  • The toolbox service in Visual Studio does not support generic types. Too awkward to prompt the programmer for the type arguments and to make it editable. This is something you have to deal with. *Encapsulation* is always the most appropriate choice for such a private implementation detail of a Form class. Expose the item collection, not the combobox. – Hans Passant Sep 14 '14 at 11:46

2 Answers2

0

the easiest way to use this GComboBox is this:

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

if you want to explicit drag from toolbox, you have to create a Class Library (From visual studio new projet) and add it to your toolbox Adding Custom Controls dll to Visual Studio ToolBox

Community
  • 1
  • 1
Mehdi Khademloo
  • 2,754
  • 2
  • 20
  • 40
0

Instead of a generic Control you can use a regular subclass with a 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 show up in the Toolbox as expected. It defaults to System.Int32 which you should adapt after placing it e.g. in the Form constructor..

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

Not sure how you would prevent wrong types being added though.. There is no ItemAdded event. This Post suggestes listening to the ComboBox messages but most posts tell you that you are in control of adding items anyway..

Community
  • 1
  • 1
TaW
  • 53,122
  • 8
  • 69
  • 111