[英]uncommitted new row not visible after add rows programmatically datagridview c#
[英]Uncommitted new row cannot be deleted in DataGridView
我在 WinForms 中有 Gridview,我想删除 GridView 中的最后一个空行我尝试使用下面的代码,但它显示错误
我的代码:
bool Empty = true;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
Empty = true;
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null && dataGridView1.Rows[i].Cells[j].Value.ToString() != "")
{
Empty = false;
break;
}
}
if (Empty)
{
dataGridView1.Rows.RemoveAt(i);
}
显示错误:
无法删除未提交的新行。
您尝试删除一行,同时仍然遍历行。 这意味着,在某个时间点之后,我将超过行数。 这可能是原因...
尝试将它们放在一个列表中,然后遍历该列表。 你只能删除然后...
例如 :
List<int> toBeDeleted = new List<int>();
// always follow conventions...
bool empty = false;
// dataGridView1.Rows.Count-1 due to AllowUserToAddRows = True
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
empty = true;
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null && dataGridView1.Rows[i].Cells[j].Value.ToString() != "")
{
empty = false;
break;
}
}
if (empty)
{
toBeDeleted.Add(i);
}
}
foreach(var f in toBeDeleted)
{
dataGridView1.Rows.RemoveAt(f);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.