删除DataGridView中的行C# [英] Delete row in a DataGridView C#
本文介绍了删除DataGridView中的行C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试循环访问我的 dataGridView1
并删除不符合条件的行如下:
I tried to loop through my dataGridView1
and remove rows which don't satisfy the condition as following:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!(Convert.ToDateTime(row.Cells[7].Value) - DateTime.Today).Days <= 0)
{
dataGridView1.Rows.Remove(row); //error: Uncommitted new row cannot be deleted.
}
}
但是我收到这个错误:
未提交的新行无法删除。
Uncommitted new row cannot be deleted.
我可以管理如果代码也是VB.NET。
I can manage if the code also VB.NET.
推荐答案
不要使用 foreach
在这种情况下,循环的集合可能被修改并导致不可预测的结果,有时会抛出异常,如集合被修改(主要在 LINQ
中遇到),使用 for
代替:
Don't use foreach
in this case, the looped collection may be modified and leads to unpredicted result, sometimes throws exception like collection was modified (encountered mainly in LINQ
), use for
instead:
for(int i = dataGridView1.RowCount-1; i >= 0; i--){
var row = dataGridView1.Rows[i];
if (!row.IsNewRow&&!(Convert.ToDateTime(row.Cells[7].Value) - DateTime.Today).Days <= 0){
dataGridView1.Rows.Remove(row);
}
}
请注意,我们必须从最大的索引循环0。
Note that we have to loop from the largest index to 0.
这篇关于删除DataGridView中的行C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文