C#: Bug in ComboBox when items are UserControls?

2019-07-31 23:35发布

问题:


I am adding objects from classes which are derived from UserControl to a ComboBox control. This is really helpful as I can access the necessary control directly from the combobox.
It all works fine EXCEPT for the fact that all ComboBox entries are empty strings (the derived UserControls behind it are fully accessible using selectedItem)...
The ComboBox uses DropDownList as its drop down style - but changing that doesn't fix it.

A minimum working example displaying empty strings:

public class TestControl : UserControl {
    public override string toString(){
        return "Example";
    }
}

...
combobox.Items.Add(new TestControl());
...

When I call

combobox.Items.Add(new TestControl().ToString());

directly, the entry is "Example".

Is this a bug in the ComboBox control or am I doing something wrong? Thank you

回答1:

Odd, that should work. Another alternative would be to set the DisplayMember property of the combobox to a property on your TestControl:

Typically, the representation of an object in the ComboBox is the string returned by that object's ToString method. If you want to have a member of the object displayed instead, choose the member that will be displayed by setting the DisplayMember property to the name of the appropriate member.

http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.items.aspx (in the remarks section)