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

时间:2010-07-14 18:03:47

标签: c# winforms data-binding combobox selecteditem

我发现很多帖子都躲过了这个话题,但实际上并没有解决这个问题。

我有一个绑定到List<State>的ComboBox,其中State是一个具有缩写和名称属性的业务对象:

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"));

最初,ComboBox显示为空白,因为未选择任何状态。如果我选中ComboBox并尝试跳出,则SelectedItem为null,但我得到一个异常:

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

在尝试将其分配给Address.State属性之前,知道为什么BindingSource似乎采用null SelectedItem并使其成为System.DBNull?在调用State setter之前,OnValidating中会发生此异常。没有调试器,看起来焦点会卡在ComboBox上。

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

1 个答案:

答案 0 :(得分:3)

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

相关问题