When you iterate over a collection using foreach, the collection should not be modified otherwise, in the best of scenarios, you end up not covering the entire collection. Most of the time, however, modifying the collection while within a foreach block, the iteration will fail.
In order to remove the rows from the DataGridView, you'll have to use a for iteration block or a two-step process both of which I display below.
for Iteration Block
This procedure uses an index to traverse the collection, modifying the collection as you go. The thing you need to know here is that if you intend to modify the collection, you do not have the index increment (go forward through the collection); you decrement the index (go backwards through the collection). If you modify (remove or add items) the collection while iterating forwards, you may not end up visiting all the items in the collection.
Here is code to remove rows from the DataGridView. Remember, we iterate backwards.
for (int i = dgv01.Rows.Count - 1; i >= 0; i--)
{
if (dgv01.Rows[i].Cells[0].Value.ToString() == "abc")
{
dgv01.Rows.RemoveAt(i);
}
}
foreach Iteration Block
This procedure uses a two-step approach. The first step finds the items to be removed and the second step removes the items from the collection. This two-step process is necessary for the reasons I explained earlier.
Now the code. Remember, it is a two-step process.
// step 1. find the items to be removed
//items to be removed will be added to this list
var itemsToRemove = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv01.Rows)
{
if (r.Cells[0].Value.ToString() == "abc")
{
itemsToRemove.Add(r);
}
}
//step 2. remove the items from the DataGridView
foreach (var r in itemsToRemove)
{
// this works because we're not iterating over the DataGridView.
dgv01.Rows.Remove(r);
}
One last thing you should know is that the procedures I have demonstrated here do not apply to the DataGridViewRowCollection class only; it applies to all collections that implement the IList<T> or the ICollection<T> interface. So, yes, the process can be used for Lists, Dictionaries, ControlCollections and all other similar classes.