Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ValueMember override an empty DisplayMember

When I set a DataSource on a control and want to use .ToString() as DisplayMember, I need to set the DisplayMember last or the ValueMember will override it.

MSDN on empty string as display member:

The controls that inherit from ListControl can display diverse types of objects. If the specified property does not exist on the object or the value of DisplayMember is an empty string (""), the results of the object's ToString method are displayed instead.

Code to reproduce:

Class:

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}";
    }
}

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 it by making a new form and adding 2 combobox's.

Result:

enter image description here

Conclusion and question:

This can be easily fixed by setting them in the correct order however this is prone to errors, it also does not show this behavior if I use an actual property as DisplayMember instead of ""/ToString.

I would really like to know why it displays this behavior and if I could possibly set .ToString() explicitly as DisplayMember (for code clarity).

like image 951
EpicKip Avatar asked Oct 29 '22 01:10

EpicKip


1 Answers

I have searched in the reference 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);

SetDataConnection method signature:

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

This sets a new DisplayMember

displayMember = newDisplayMember;

so now we've come to the root of the issue

like image 166
EpicKip Avatar answered Nov 15 '22 04:11

EpicKip