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

Winforms 如何将BindingSource当前记录设置为null?,winforms,data-binding,bindingsource,Winforms,Data Binding,Bindingsource,我有一个工单的捕获表单,它有一个CustomerBindingSource和一个WorksOrderBindingSource控件。大多数编辑字段都绑定到WorksOrderBindingSource,其中一个组合框的列表绑定到CustomerBindingSource,其SelectedValue绑定到WorksOrderBindingSource中的CustomerId字段。这是非常常规和标准的,这里没有搞笑 然后,我还有一些文本框字段,用于显示当前编辑的工单的当前选定客户的属性。我还将这些

我有一个工单的捕获表单,它有一个
CustomerBindingSource
和一个
WorksOrderBindingSource
控件。大多数编辑字段都绑定到
WorksOrderBindingSource
,其中一个组合框的列表绑定到
CustomerBindingSource
,其
SelectedValue
绑定到
WorksOrderBindingSource
中的
CustomerId
字段。这是非常常规和标准的,这里没有搞笑

然后,我还有一些文本框字段,用于显示当前编辑的工单的当前选定客户的属性。我还将这些字段绑定到
CustomerBindingSource
。选择客户后,这些字段将按预期显示该客户的属性

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

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

我用来“清除”BindingSource的方法是简单地将其数据源设置为:

CustomerBindingSource.DataSource=类型(客户)

希望这有帮助

编辑:

为清楚起见,当您按照所述设置BindingSource.DataSource属性时,不会阻止您在以后重新分配原始数据源:

//Retrieve customers from database
List<Customer> Customers = WhatEverCallToDB();
CustomerBindingSource.DataSource = Customers;

...

//Later we need to blank the Customer fields on the Windows Form
CustomerBindingSource.DataSource = typeof(Customer);

...

//Then again at a later point we can restore the BindingSource:
CustomerBindingSource.DataSource = Customers;

...
//从数据库中检索客户
列出客户=WhatEverCallToDB();
CustomerBindingSource.DataSource=客户;
...
//稍后,我们需要清空Windows窗体上的客户字段
CustomerBindingSource.DataSource=类型(客户);
...
//之后,我们可以再次恢复BindingSource:
CustomerBindingSource.DataSource=客户;
...

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

我最终得到了一个可行的解决方案:我向bindingsource(将是您的CustomerBindingSource)添加了一个[PositionChanged]事件

private void CustomerBindingSource\u位置已更改(对象发送方,事件参数e)
{
如果(.SelectedIndex==-1)
{
CustomerBindingSource.SuspendBinding();
}
其他的
{
CustomerBindingSource.ResumeBinding();
}
}

为什么不将“请选择客户”项添加到绑定源?如何强制用户保存当前编辑,以便为您的新行分配有效的CustomerID?我不想清除绑定源。我想让大家知道,绑定源中没有一条记录被选中,或者“活动”。我想你的意思是,当你创建一个新的工作订单时,你想“清空”与客户相关的字段。如果是这样,那么我的方法将起作用,但是如果我误解了您的用例,您能澄清一下吗?我确实想清空与客户相关的字段,但我不想丢失
CustomerBindingSource.DataSource
中的客户记录集。我只希望这些记录都不被选中。好吧,在代码中,您必须已经有了对数据对象的引用,即保存客户记录的对象,例如DataTable或其他什么。因此,使用我描述的技术,您不会丢失引用。您仍然可以在以后重新分配CustomerBindingSource.DataSource=MyCustomerDataObject。何时设置
DataSource=typeof(Customer)
?当需要时,清除选择是在我添加新工作订单时,但用户需要有客户从中进行选择。
        private void CustomerBindingSource_PositionChanged(object sender, EventArgs e)
    {
        if(<yourCombobox>.SelectedIndex==-1)
        {
            CustomerBindingSource.SuspendBinding();
        }
        else
        {
            CustomerBindingSource.ResumeBinding();
        }
    }