[英]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.