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?