且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当SelectedItem为null时,对象绑定到Winforms ComboBox失败

更新时间:2022-10-21 13:22:25

这是因为控件验证是Binding类的默认值。您可能需要将Binding.DataSourceUpdateMode属性更改为DataSourceUpdateMode.OnPropertyChanged,因此只有在用户更改组合框选择时才分配值。


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?

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.