2015-02-06 75 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

相關問題