When I set the DataSource in the control and want to use .ToString() as DisplayMember , I need to set DisplayMember last, or ValueMember override it.
MSDN in an empty line as a display element:
The controls that inherit ListControl can display various types of objects. If the specified property does not exist on the object or the DisplayMember value is an empty string (""), the results of the object's ToString method are displayed instead.
Code to play:
Grade:
class SomeClass { public string PartA { get; set; } public string PartB { get; set; } public string WrongPart { get { return "WRONG"; } } public override string ToString() { return $"{PartA} - {PartB}"; } }
The form:
var testObj = new SomeClass() { PartA = "A", PartB = "B" }; comboBox1.DataSource = new [] { testObj }; comboBox1.DisplayMember = ""; comboBox1.ValueMember = "WrongPart"; comboBox2.DataSource = new[] { testObj }; comboBox2.ValueMember = "WrongPart"; comboBox2.DisplayMember = "";
You can try by creating a new form and adding 2 combobox.
Result:

Conclusion and question:
This can be easily fixed by setting them in the correct order, but it is error prone but also does not show this behavior if I use the actual property as DisplayMember instead of "" / ToString .
I would really like to know why it displays this behavior, and if I could set .ToString() explicitly as DisplayMember (for clarity of code).
source share