2011-07-07 136 views
1

我有一个DataGridView集合对象并检查特定条件。如果它为空,那么我将它从DataGridView集合中删除。这里是我的代码 -从集合中删除

foreach(DataGridViewRow dr in myDataGridViewRowCollection.Rows) 
{ 
    string title = TypeConvert.ToString(dr.Cells[Name].Value); 
    if(title == null) 
     //Remove it from the list. 
     myDataGridViewRowCollection.Rows.Remove(dr); 
} 

现在,如果我有6排在myDataGridViewRowCollection和他们,其中5有标题为空。现在,上面的代码只删除了5个中的3个,而不是剩下的两个。

我有点理解这个问题,但我现在不能想到的一个解决方案。有什么想法吗?

回答

3

问题是,当您迭代它时会更改myDataGridViewRowCollection.Rows集合,这会混淆/破坏迭代器。你需要分成两步。首先列出你需要删除的内容,然后你可以删除它们。

var toRemove = myDataGridViewRowCollection.Rows.Where(x => x.Cells[Name].Value == null); 

foreach(var row in toRemove){ 
    myDataGridViewRowCollection.Rows.Remove(row); 
}