如何将BindingSource当前记录设置为null?

Pro*_*ofK 6 data-binding bindingsource winforms

我有一个工作订单的捕获表单,它有一个CustomerBindingSource和一个WorksOrderBindingSource控件.大多数编辑字段都绑定到WorksOrderBindingSource,其中一个ComboBox的列表绑定到CustomerBindingSource,并且它SelectedValue绑定到的CustomerId字段WorksOrderBindingSource.这都是非常常规和标准的,这里没有任何好玩的东西.

然后,我还有一些文本框字段,我用它来显示当前所选客户的属性,用于当前编辑的工单.我也将这些领域捆绑在一起CustomerBindingSource.选择客户后,这些字段会按预期显示该客户的属性.

我的问题是当我想使用表单捕获新的工作订单时.我实例化一个新WorksOrder对象,CustomerId == null并将其绑定到WorksOrderBindingSource.我在没有对象CustomerBindingSourceId == null,因此,如预期,下拉组合框为空,但是,该CustomerBindingSource.Current属性指向该数据源的第一个客户对象.客户链接的显示字段显示该客户的值,而尚未选择任何客户.

对我而言,唯一可行的解​​决办法似乎很笨拙.在其中,我有两个客户类型的绑定源,一个用于选定的客户,并填充客户显示字段,另一个仅用于填充客户下拉列表.然后,我必须处理选择事件,并且仅当选择了客户时,才在显示字段的绑定源中找到该客户,如果没有选择,则将显示字段的数据源设置为null.这感觉非常笨拙.有没有其他方法可以实现我想要的?

小智 2

我发现这个主题正是我的问题,但没有令人满意的答案。我知道这是一个老话题,但是啊..

我最终得到了一个有效的解决方案:我将 [PositionChanged] 事件添加到我的绑定源(将是您的 CustomerBindingSource)。

        private void CustomerBindingSource_PositionChanged(object sender, EventArgs e)
    {
        if(<yourCombobox>.SelectedIndex==-1)
        {
            CustomerBindingSource.SuspendBinding();
        }
        else
        {
            CustomerBindingSource.ResumeBinding();
        }
    }
Run Code Online (Sandbox Code Playgroud)