Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView Removing Rows removes only alternate rows

I have 100 rows in a DataGridView. I then remove each row as shown below but as it loops around the ID is coming in as 0,2,4,6,8 and therefore its removing only even rows. What's going on?

                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;
                    }
                }
like image 961
Jon Avatar asked Jan 20 '23 09:01

Jon


1 Answers

I believe as you loop through the grid and delete the current row, its messing up with the index of the grid which as of now would be causing the rows to shift a level up. So as you proceed further to the next row it has already moved to the index wherein you deleted the row.

Your best bet would be use a for loop and run it reverse and this should work out fine.

like image 124
V4Vendetta Avatar answered Jan 30 '23 23:01

V4Vendetta