2015-02-06 73 views
1

我想从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

如果你想,你遍历它像这样从集合中删除的项目,你需要通过行集合向后工作:

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

只是为了使它不那么维修头部疼痛,你可能想使用的列名,而不是列索引太...只是思想。

+0

在第二个代码块中调用'ToList()'避免了“集合被修改了”InvalidOperationException。应该工作得很好,除非你的DataGridView有一百万行或... – 2015-02-06 04:06:19

+0

非常感谢Mr.Winney :-)它的工作完美:-) – 2015-02-06 04:16:02

+0

好听。别客气。 :) – 2015-02-06 04:17:28

相关问题