【问题标题】:DataGridView delete row when DataSource is List<myClass>DataSource 为 List<myClass> 时 DataGridView 删除行
【发布时间】:2014-02-05 08:40:21
【问题描述】:

在我的DataGridView 上,我已将 AllowUserToDeleteRows 设置为 True。

当我将DataGridViewDataSource 设置为IQueryable

var dc = new Data.CustomersDataContext();
var q = dc.Customers;
dataGridView1.DataSource = q;

我可以从中删除行,但是当我将其设置为 List&lt;T&gt;

var dc = new Data.CustomersDataContext();
var l = dc.Customers.ToList();
dataGridView1.DataSource = l;

我不能再删除行(当我按下删除按钮时没有任何反应)

如何将我的DataSource 保留为List&lt;T&gt; 并且还能够删除行?

【问题讨论】:

  • 客户是否有结构或类实例列表?
  • @Junaith 我不知道。这是 Linq-to-Sql 生成的。
  • @Junaith 我检查了我的 dbml 设计器,它是客户列表,其中客户是从 INotifyPropertyChanging、INotifyPropertyChanged 派生的类

标签: c# linq datagridview iqueryable


【解决方案1】:

发生这种情况是因为 DataGridView 仅在绑定到 IBindingList 实现时才允许删除行(请参阅下面的注释),并且 IBindingList.AllowRemove 返回 true。

您可以将列表包装到BindingList&lt;T&gt;,默认情况下允许删除项目:

dataGridView1.DataSource = new BindingList<Customer>(dc.Customers.ToList());

注意。 Data.CustomersDataContext.Customers 实现 IListSource,它返回 IBindingListAllowRemove == true,这就是您的第一个案例按预期工作的原因。 DGV 知道 IListSource 并使用 IListSource.GetList() 结果作为数据源。

【讨论】:

    猜你喜欢
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多