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

Had*_*ter 4 c# data-binding combobox selecteditem winforms

我发现很多帖子都回避了这个话题,但没有一个真正解决这个问题。

我有一个绑定到 a 的 ComboBox List<State>,其中 State 是具有 Abbreviation 和 Name 属性的业务对象:

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"));
Run Code Online (Sandbox Code Playgroud)

最初,组合框显示空白,因为未选择任何状态。如果我按 Tab 键切换到 ComboBox 并尝试按 Tab 键退出,则 SelectedItem 为 null,但出现异常:

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

知道为什么 BindingSource 似乎会采用 null SelectedItem 并将其设置为 System.DBNull,然后再尝试将其分配给 Address.State 属性吗?在调用我的 State setter 之前,此异常发生在 OnValidating 中。如果没有调试器,焦点似乎会停留在组合框上。

我不想将空缩写和名称的空 State 对象添加到我的数据源中。我该如何解决这个问题?

Han*_*ant 5

这是因为控件验证是 Binding 类的默认设置。您可能希望将 Binding.DataSourceUpdateMode 属性更改为 DataSourceUpdateMode.OnPropertyChanged,以便仅在用户更改组合框选择时才分配值。