I have a DataGridView collection object and check for a particular condition. If it is null, then I remove it from the DataGridView Collection. Here is my code –
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);
}
Now if I have 6 Rows in the myDataGridViewRowCollection and of them, 5 of them have title as null. Now, the above code removes only 3 of the 5 and not the remaining two.
I kind of understand the problem but I am not able to think right now of a solution. Any thoughts?
The problem is that you’re changing the
myDataGridViewRowCollection.Rowscollection as you’re iterating over it, which confuses/breaks the iterator. You need to seperate this into two steps. First make a list of what you need to remove, then you can actually remove them.