C# – DisplayMember getting reset on DataSource=null


I have a ComboBox whose items are set using the DataSource property. The DataSource is a collection of a custom object (that has a string property 'Value' and int property 'Id'). In the initialise controls, I set the DisplayMember as Value and ValueMember as Id. Now I tried to clear the DataSource by calling,

myComboBox.DataSource = null;

When I did that, my DisplayMember is reset to "" automatically. Am I clearing the DataSource properly ?? Is that the way I should behave ???

Best Solution

I can reproduce it... it isn't something I would have expected, but it looks like you'll simply have to set the DisplayMember back afterwards.

Looking in reflector, this is quite intentional:

        if (value == null)
            this.DisplayMember = "";

Not sure of the reasoning behind that, but simply:

string oldDisplayMember = cbo.DisplayMember;
cbo.DataSource = null;
cbo.DisplayMember = oldDisplayMember;

Not pretty, but it'll work.

Related Question