【问题标题】:How can I set a BindingSource current record to null?如何将 BindingSource 当前记录设置为空?
【发布时间】:2012-09-27 06:28:32
【问题描述】:

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

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

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

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

【问题讨论】:

  • 为什么不向绑定源添加“please-select-a-customer”项?
  • 如何强制用户保存当前编辑,以便将有效的 CustomerID 分配给您的 NewRow

标签: winforms data-binding bindingsource


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我用来“清除” BindingSource 的方法是像这样简单地设置它的 DataSource:

    CustomerBindingSource.DataSource = typeof(Customer);

    希望这会有所帮助。

    编辑:

    为清楚起见,当您按照描述设置 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;
    
    ...
    

    【讨论】:

    • 我不想清除绑定源。我希望知道绑定源中没有一条记录被选中或“激活”。
    • 我以为你的意思是当你创建一个新的 WorkOrder 时,你想“清空”与客户相关的字段。如果是这样,那么我的方法会起作用,但是如果我误解了你的用例,你能澄清一下吗?
    • 我确实想清空与客户相关的字段,但我不想丢失CustomerBindingSource.DataSource 中的客户记录集。我只是不想选择这些记录。
    • 好的,在您的代码中,您必须已经拥有对数据对象的引用,即保存客户记录的数据对象,例如 DataTable 或其他。因此,使用我描述的技术,您不会丢失该参考。您仍然可以稍后重新分配 CustomerBindingSource.DataSource = MyCustomerDataObject。
    • 什么时候设置DataSource = typeof(Customer)?何时需要清除选择是当我添加一个新的 WorksOrder 时,但随后用户需要有客户可供选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 2020-03-12
    • 2014-03-25
    相关资源
    最近更新 更多