views:

23

answers:

1

I found a lot of posts that dodge this topic, but none that actually addresses this case.

I have a ComboBox bound to a List<State>, where State is a business object that has Abbreviation and Name properties:

this._stateComboBox.DataSource = ((Address)this._addressBindingSource.DataSource).States;
this._stateComboBox.DisplayMember = "Abbreviation";
this._stateComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this._addressBindingSource, "State"));

Initially the ComboBox displays blank as no State is selected. If I tab to the ComboBox and try to tab out, the SelectedItem is null, but I get an exception:

Object of type 'System.DBNull' cannot be converted to type 'State'.

Any idea why the BindingSource appears to be taking the null SelectedItem and making it System.DBNull before trying to assign it to the Address.State property? This exception occurs in OnValidating before my State setter is called. Without debugger, it looks like the focus gets stuck at the ComboBox.

I don't want to have to add an empty State object to my data source with empty Abbreviation and Name. How can I work around this problem?

+1  A: 

It is because control validation is the default for the Binding class. You might want to change the Binding.DataSourceUpdateMode property to DataSourceUpdateMode.OnPropertyChanged so a value is only assigned when the user changes the combo box selection.

Hans Passant
That didn't quite work well for me; however it did give me a hint that led me to a workaround:I am now setting DataSourceNullValue = null when creating the Binding object. Although this lets me bypass the exception, it unfortunately does not allow me to commit a value of null. In other words, if I wipe out my control's displayed value, the non-null property value is retrieved from the bound object during validation, rather than setting the bound object property to null.
Hadster