当SelectedItem为null时,对象绑定到Winforms ComboBox失败 [英] Object binding to Winforms ComboBox fails when SelectedItem is null

查看:124
本文介绍了当SelectedItem为null时,对象绑定到Winforms ComboBox失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

  ._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并尝试tab出来,SelectedItem是null,但是我得到一个异常:



DBNull'不能转换为类型'State'。



任何想法为什么BindingSource看起来采用null SelectedItem并使其成为System。 DBNull之前尝试将其分配给Address.State属性?在调用我的状态设置器之前,OnValidating中发生此异常。没有调试器,它看起来像焦点停留在ComboBox。



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

解决方案

这是因为控件验证是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.

这篇关于当SelectedItem为null时,对象绑定到Winforms ComboBox失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆