10

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 ???

2 Answers 2

4

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.

1
  • Well, "functions as written" ;-p But it does violate a few typical property behaviours (i.e. unexpected side-effects). Mar 13, 2009 at 8:23
0

When there is an Exception thrown or if the Datasource value is null, then the Displaymember is set to an empty string.

Using a .NET code decompiler, there are comments in the code about how this works. I'll try to paraphrase.

Exceptions may be thrown in the following circumstances:

  1. Application code on DataSourceChanged
  2. During binding when the data is being formatted for display
  3. If the DisplayMember value isn't valid in the new Datasource.

The comment also mentions that the actual exception is "swallowed" to keep from breaking expected behavior.

I personally ran into this behavior and since the exception isn't thrown it's difficult to figure out which of these conditions caused the reset. There is probably a better way but for now I'm using this in my custom control. The Datasource property is valid when setting the DisplayMember after it's been reset so I'm really not sure about why it's failing :

    public new object DataSource
    {
        get { return base.DataSource; }
        set
        {
            string displayMem = this.DisplayMember;
            base.DataSource = value;
            if (string.IsNullOrEmpty(this.DisplayMember) && string.IsNullOrEmpty(displayMem)) 
                this.DisplayMember = displayMem;
            DetermineDropDownWidth();
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.