[英]Delete multiples rows in DataGridViews
我有一个父类定义如下:
using System.Collections.Generic;
namespace Test
{
public class GeneralClass
{
public class Parent
{
public string Parent_Name { get; set; }
public List<Child> List_Child { get; set; } = new List<Child>();
}
public class Child
{
public string Child_Name { get; set; }
}
}
}
请注意,Child_Name具有以下格式:Parent_Name +“ - ”+整数。
然后在同一个Form中,我创建了两个DataGridView(dt1和dt2)。 在dt1上,每一行显示Parent_Name,在dt2上每行显示Child_Name。 每个父母可以有多个孩子(List)。
现在我想: - 删除dt1上的父(一行),它也会删除dt2中的所有关联子项(但不删除其他父项的子项)。
到目前为止,我所做的是
// Iteration over selected parents
foreach (DataGridViewRow row_dt1 in dt1.SelectedRows)
{
if (!row.IsNewRow)
{
// Find parent name of actual row
string parent_name = row_dt1.Cells[0].Value.ToString();
// Iteration over all rows of children
foreach (DataGridViewRow row_dt2 in dt2.Rows)
{
// Find child name
object val1 = row_dt2.Cells[0].Value;
// If child name starts with parent name, remove this child from the DataGridView (dt2)
if (val1 != null && val1.ToString().StartsWith(parent_name + "-"))
{
dt2.Rows.Remove(row_dt2);
}
}
// Now remove the parent from dt1
dt1.Rows.Remove(row_dt1);
}
}
它按预期删除了选定的父级,但它只删除了该父级的第一个子级(但不删除其他父级)。 我哪里做错了?
非常感谢你!
您不应该尝试从正在迭代的同一个集合中删除项目。
如果从集合中删除一个项目,则foreach迭代器将处于不可能的状态。 它将无法再正确地找到迭代中的下一行。 这就像锯你坐的树枝一样
这里使用的老技巧是从集合中的最后一项开始 ,使用正常的for..loop导航行集合 。 因此,当您删除项目时,计数器(x)会减少,并且您不会跳过循环中的任何行。
foreach (DataGridViewRow row_dt1 in dt1.SelectedRows)
{
if (!row.IsNewRow)
{
// Find parent name of actual row
string parent_name = row_dt1.Cells[0].Value.ToString();
// Iteration over all rows of children
for(int x = dt2.Rows.Count - 1; x >= 0; x--)
{
// Find child name
DataGridViewRow row_dt2 = dt2.Rows[x];
object val1 = row_dt2.Cells[0].Value;
// If child name starts with parent name, remove this child from the DataGridView (dt2)
if (val1 != null && val1.ToString().StartsWith(parent_name + "-"))
{
dt2.Rows.Remove(row_dt2);
}
}
// Now remove the parent from dt1
dt1.Rows.Remove(row_dt1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.