DataGridView Removing Rows removes only alternate rows

I have 100 rows in a DataGridView. Then I delete each line as shown below, but as it goes around the identifier, it appears as 0,2,4,6,8 and therefore only deletes even lines. What's happening?

foreach (DataGridViewRow row in dgvData.Rows) { try { if (row.IsNewRow) continue; string PalletID = row.Cells[1].Value.ToString(); string Location = row.Cells[2].Value.ToString(); dgvData.Rows.Remove(row); AddToList(PalletID + " located in " + Location + " was uploaded"); } catch (Exception ex) { MessageBox.Show("Error Uploading Data"); AddToList("Error uploading data " + ex.Message); continue; } } 
+4
source share
4 answers

I believe when you scroll the grid and delete the current row, its mess with the grid index, which at the moment will cause the rows to move up. As you move to the next row, it has already moved to the index where you deleted the row.

It is best to use a for loop and run it in reverse order, and this should work out in order.

+7
source

The problem is that you changed dgvData.Rows during the loop cycle. I think you need to use for instead of foreach if you want to remove elements in a loop.

EDIT . To be more clear:

when you delete row c in the foreach , the first time you delete dgvData.Rows[0] , and dgvData.Rows[1] becomes the new dgvData.Rows[0] . Therefore, the second time it deletes dgvData.Rows[1] , it completely deletes the original dgvData.Rows[2] .. etc.

+1
source

try it

 for (int i = dgvData.Rows.Count - 1; i >= 0; i--) { dgvData.Rows.Remove(dgvData.Rows[i]); } 

you use a ForEach loop and delete the rows of the same collection, i.e. dgvData.Rows. This is his missing object from this collection and failed to skip every item.
So in order to deal with this, you need to get hung up on using the above code.

You need to set the value i accordingly for the new line, if it allows you to add a new line ....

+1
source

The only thing that is possible for me is that

  if (row.IsNewRow) continue; 

allows you to skip some lines that have these properties ... Try placing a debug message there.

0
source

All Articles