开发者

DataGridView Removing Rows removes only alternate rows

开发者 https://www.devze.com 2023-03-15 17:05 出处:网络
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?

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 Pallet开发者_Go百科ID = 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;
                    }
                }


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.


The problem is because you have changed dgvData.Rows during the process of loop through it. I think you need to use for instead of foreach, if you want to remove items within the loop.

EDIT To be more clear:

when you delete the row with in the foreach loop, the first time it will delete dgvData.Rows[0], and the dgvData.Rows[1] will become the new dgvData.Rows[0]. So the second time when it delete dgvData.Rows[1] it actrully deleted the original dgvData.Rows[2].. etc.


try this

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

you are using ForEach loop and deleting rows of the same collection, ie dgvData.Rows. That is its missing a object from that collection and failed to loop through each item.
So to handle this you need to loop from behind using the above code.

You need to set the value of i accordingly for the new row if it allows adding new row....


The only thing that is possible to me, is that

 if (row.IsNewRow)
     continue;

let's you skip some rows that have that properties... Try to place there some debug message.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号