简体   繁体   English

如何删除DataGridView中的多行?

[英]How to delete multiple rows in DataGridView?

I have a DataGridView on a winform.我在 winform 上有一个 DataGridView。 Below is a working sample that repros the problem.下面是重现问题的工作示例。 The grid has two columns - checkbox and textbox.网格有两列 - 复选框和文本框。 I'm creating two rows of data.我正在创建两行数据。

I loop through and get any checked row.我循环并获取任何选中的行。 Then I try to delete them.然后我尝试删除它们。 In the loop where I'm removing rows, all goes well on the first iteration.在我删除行的循环中,第一次迭代一切顺利。 r.Index is 0. r.Index为 0。

Coming into the second iteration is where things breakdown.进入第二次迭代是事情崩溃的地方。 r.Index is now -1 and r.Cells[1].Value is null. r.Index现在为 -1, r.Cells[1].Value为空。

Why is this happening and what is the right way to remove these rows?为什么会发生这种情况以及删除这些行的正确方法是什么?

public Form1() 
{
List<data> dataList = new List<data>();
dataList.Add(new data() {IsChecked=true, dept="dept1"});
dataList.Add(new data() {IsChecked=true, dept="dept2"});
BindingListView<data> view = new BindingListView<data>(dataList);
dataGridView1.DataSource = view;

var rows = SelectedRows();
foreach (DataGridViewRow r in rows) {
  var name = r.Cells[1].Value.ToString();
  dataGridView1.Rows.Remove(r);
}

List<DataGridViewRow> SelectedRows() {
  List<DataGridViewRow> rows = new List<DataGridViewRow>();
  foreach (DataGridViewRow row in dataGridView1.Rows) {
    if (Convert.ToBoolean(row.Cells[0].Value)) {
      rows.Add(row);
    }
   }
   return rows;
}

}


public class data 
{
  public bool IsChecked {get;set;}
  public string dept {get;set;}
}

BindingListView class comes from here: http://blw.sourceforge.net BindingListView 类来自这里: http : //blw.sourceforge.net

You can remove checked item from the BindingListView<Data> .您可以从BindingListView<Data>删除选中的项目。 The changes will be shown in DataGridView immediately.更改将立即显示在DataGridView

foreach (var item in view.ToList())
{
    if (item.IsChecked)
        view.Remove(item);
}

Using ToList() creates a different List<Data> which is used in the loop, so removing the item from original list is allowed and doesn't change the list we used in the loop.使用ToList()创建一个不同的List<Data>用于循环,因此允许从原始列表中删除项目并且不会更改我们在循环中使用的列表。

Also as another option, you can remove the row from DataGridView this way.作为另一种选择,您可以通过这种方式从DataGridView删除该行。 The changes will be made in the BindingListView<Data> immediately:将立即在BindingListView<Data>进行更改:

dataGridView1.Rows.Cast<DataGridViewRow>()
    .Where(row => (bool?)row.Cells[0].Value == true)
    .ToList().ForEach(row =>
    {
        dataGridView1.Rows.Remove(row);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM