C# 如何在不使用索引的情况下从datagridview中删除多行?

C# 如何在不使用索引的情况下从datagridview中删除多行?,c#,datagridview,C#,Datagridview,我想从datagridview中删除多行, 我尝试了下面的代码,这里的行是根据索引被删除的 for (int m = 0; m < dataGridView3.Rows.Count - 1; m++) { if (dataGridView3.Rows[m].Cells[2].Value != null) { for (int n = 0; n < dataGridView2.Rows.Co

我想从datagridview中删除多行, 我尝试了下面的代码,这里的行是根据索引被删除的

for (int m = 0; m < dataGridView3.Rows.Count - 1; m++)
        {
            if (dataGridView3.Rows[m].Cells[2].Value != null)
            {
                for (int n = 0; n < dataGridView2.Rows.Count - 1; n++)
                {
                    if (dataGridView2.Rows[n].Cells[2].Value != null)
                    {

                        if (dataGridView2.Rows[n].Cells[2].Value.Equals(dataGridView3.Rows[m].Cells[2].Value) &&
                            dataGridView2.Rows[n].Cells[8].Value.Equals(dataGridView3.Rows[m].Cells[8].Value))
                        {
                            dataGridView2.Rows.RemoveAt(n);
                            //break;
                        }
                    }
                }
            }
        }
for(int m=0;m
这里并没有正确地删除行,因为每次删除后索引都会更改,所以循环中会丢失一些记录


有谁能帮我解决这个问题吗?

如果要像这样在集合中进行迭代时从集合中删除项,则需要在行集合中进行反向操作:

// start with the last row, and work towards the first
for (int n = dataGridView2.Rows.Count - 1; n >= 0; n--)
{
    if (dataGridView2.Rows[n].Cells[2].Value != null)
    {
        if (dataGridView2.Rows[n].Cells[2].Value.Equals(dataGridView3.Rows[m].Cells[2].Value) &&
            dataGridView2.Rows[n].Cells[8].Value.Equals(dataGridView3.Rows[m].Cells[8].Value))
        {
            dataGridView2.Rows.RemoveAt(n);
            //break;
        }
    }
}
或者,您可以使用LINQ先查找匹配项,然后删除它们:

var rowToMatch = dataGridView3.Rows[m];

var matches =
    dataGridView2.Rows.Cast<DataGridViewRow>()
                 .Where(row => row.Cells[2].Value.Equals(rowToMatch.Cells[2].Value)
                               && row.Cells[8].Value.Equals(rowToMatch.Cells[8].Value))
                 .ToList();

foreach (var match in matches)
    dataGridView2.Rows.Remove(match);
var rowToMatch=dataGridView3.Rows[m];
变量匹配=
dataGridView2.Rows.Cast()
.Where(row=>row.Cells[2].Value.Equals(rowToMatch.Cells[2].Value)
&&row.Cells[8].Value.Equals(rowToMatch.Cells[8].Value))
.ToList();
foreach(匹配中的变量匹配)
dataGridView2.Rows.Remove(匹配);

为了减少维护时的头痛,您可能也希望使用列名而不是列索引。。。只是想一想。

非常感谢您Winney先生:-)它工作得很好:-)