Why ValueMember Overrides Empty DisplayMember

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:

enter image description here

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

+5
source share
1 answer

I searched in the source source and found this bit:

 if (!newValueMember.Equals(valueMember)) { // If the displayMember is set to the EmptyString, then recreate the dataConnection // if (DisplayMember.Length == 0) SetDataConnection(DataSource, newValueMember, false); 

Signature of the SetDataConnection method:

 private void SetDataConnection(object newDataSource, BindingMemberInfo newDisplayMember, bool force) 

This sets up a new DisplayMember.

 displayMember = newDisplayMember; 

So now we have come to the root of the problem

+2
source

Source: https://habr.com/ru/post/1272042/


All Articles