【问题标题】:How to clear a binding source?如何清除绑定源?
【发布时间】:2015-02-26 13:16:52
【问题描述】:

我有这个模型:

public class CustomerType
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string Description {get; set;}
}

然后,我在 WinForms 表单上有一个绑定源,并通过执行以下操作将其绑定到现有对象:

var customerType = repository.Get(id);
bindingSource.DataSource = customerType;

我想清除数据源,所以我这样做:

bindingSource.DataSource = null;

但我得到以下异常:Cannot bind to the property or column Name on the DataSource.

将变量 customerType 设置为 null 不会清除数据源。

那么清除数据源的正确方法是什么?

【问题讨论】:

  • 没有bindingSource.Clear()吗?
  • BindingSource 实现 IList 所以是的,有一个 bindingSource.CLear()
  • 数据源只是一个 POCO 对象。

标签: c# winforms data-binding


【解决方案1】:

你可以试试

bindingSource.DataSource = typeof(CustomerType);

这是 Visual Studio 默认分配的。

【讨论】:

  • 这确实清除了绑定源的数据源。但是如果我将变量customerType 设置为null,则不会清除数据源。应该清除吗?
  • @Ivan-MarkDebono:我不明白,它是否有效?我不知道如果您分配null,为什么BindingSource 拒绝工作。我猜是因为您使用自定义类型作为源。错误信息相当清楚。 BindingSource 正在寻找一个Name 属性,null 没有这个属性,它属于CustomerType 类型。
  • 我发现这个相关:stackoverflow.com/questions/220392/…
【解决方案2】:

首先,清空数据源:

this.bindingSource.DataSource = null;

然后清除行:

this.bindingSource.Rows.Clear();

然后将数据源设置为新列表:

this.bindingSource.DataSource = this.GetNewValues();

【讨论】:

  • 正如他提到的将DataSource设置为null会引发异常
猜你喜欢
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 2013-01-01
  • 2015-05-06
  • 2015-09-10
  • 2012-02-16
  • 1970-01-01
相关资源
最近更新 更多