【发布时间】:2011-03-16 00:15:17
【问题描述】:
我发现很多帖子都在回避这个话题,但没有一个真正解决这个问题。
我有一个绑定到 List<State> 的 ComboBox,其中 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"));
最初 ComboBox 显示空白,因为没有选择任何状态。如果我跳到 ComboBox 并尝试跳出,SelectedItem 为空,但我得到一个异常:
Object of type 'System.DBNull' cannot be converted to type 'State'.
知道为什么 BindingSource 在尝试将其分配给 Address.State 属性之前似乎采用 null SelectedItem 并将其设为 System.DBNull 吗?在调用我的 State setter 之前,此异常发生在 OnValidating 中。如果没有调试器,看起来焦点会卡在 ComboBox 上。
我不想在我的数据源中添加一个空的 State 对象,而 Abbreviation 和 Name 都是空的。我该如何解决这个问题?
【问题讨论】:
标签: c# winforms data-binding combobox selecteditem