如何在DataGridView中删除多行? [英] How to delete multiple rows in DataGridView?
问题描述
我在winform上有一个DataGridView。下面是一个解决此问题的工作示例。网格有两列-复选框和文本框。我正在创建两行数据。
I have a DataGridView on a winform. Below is a working sample that repros the problem. The grid has two columns - checkbox and textbox. I'm creating two rows of data.
我遍历并获取任何选中的行。然后,我尝试将其删除。在我要删除行的循环中,所有操作在第一次迭代中都进展顺利。 r.Index
为0。
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
现在为-1, r.Cells [1] .Value
为空。
Coming into the second iteration is where things breakdown. r.Index
is now -1 and r.Cells[1].Value
is null.
为什么会这样,删除这些行的正确方法是什么?
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类来自这里: http://blw.sourceforge.net
BindingListView class comes from here: http://blw.sourceforge.net
推荐答案
您可以从 BindingListView< Data>
中删除选中的项目。更改将立即显示在 DataGridView
中。
You can remove checked item from the BindingListView<Data>
. The changes will be shown in DataGridView
immediately.
foreach (var item in view.ToList())
{
if (item.IsChecked)
view.Remove(item);
}
使用 ToList()
创建另一个在循环中使用的 List< Data>
,因此允许从原始列表中删除该项目,并且不会更改我们在循环中使用的列表。
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.
另外,您还可以通过这种方式从 DataGridView
中删除行。更改将立即在 BindingListView< Data>
中进行:
Also as another option, you can remove the row from DataGridView
this way. The changes will be made in the BindingListView<Data>
immediately:
dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => (bool?)row.Cells[0].Value == true)
.ToList().ForEach(row =>
{
dataGridView1.Rows.Remove(row);
});
这篇关于如何在DataGridView中删除多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!