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 OnValidati开发者_如何学编程ng 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?
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.
精彩评论