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

时间:2015-02-06 03:12:41

标签: 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.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;
                        }
                    }
                }
            }
        }

这里的行没有被正确删除,因为在每次删除后都会更改索引,因此有些记录会从循环中丢失。

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

如果您在这样迭代时要从集合中删除项目,那么您需要在行集合中向后工作:

// 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);

为了减少维护工作量,你可能想要使用列名而不是列索引......只是想一想。