Generic ComboBox in Windows Forms Application

放肆的年华 提交于 2019-12-13 00:52:05

问题


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?


回答1:


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




回答2:


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..



来源:https://stackoverflow.com/questions/25832626/generic-combobox-in-windows-forms-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!