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

发布于 2024-09-10 05:51:18 字数 818 浏览 6 评论 0原文

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

我有一个绑定到 List 的 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 显示为空白,因为未选择任何 State。如果我按 Tab 键切换到 ComboBox 并尝试按 Tab 键退出,则 SelectedItem 为空,但出现异常:

Object of type 'System.DBNull'无法转换为类型'State'。

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

香橙ぽ 2024-09-17 05:51:18

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文