简体   繁体   中英

Why does the DataTable.Rows.Count not change after deleting rows?

In my project I need to delete all records from a DataTable, so I tried this code :

while (DataTable1.Rows.Count > 0)
    DataTable1.Rows[0].Delete();

but this is an infinite loop, it seems that after the Delete() statement the Rows.Count does not changes.

It appears the records are still there but marked for deletion.
So I change my count to this :

int count = DataTable1.Select("", "", DataViewRowState.CurrentRows).Count();

So now I can change my loop like this

int count = DataTable1.Select("","",DataViewRowState.CurrentRows).Count();
while (count > 0)
{
    DataTable1.Rows[0].Delete(); // THIS IS WRONG NOW
    count = DataTable1.Select("","",DataViewRowState.CurrentRows).Count();
}

Now the count does counts down as expected, but now I have a problem with the Rows[0].Delete() statement.

It will delete the same row over and over again.

So my question is, how can I find the first row that is not deleted, and delete it ?
In other words, the line that is commented with // THIS IS WRONG NOW what can I use at that line ?

Or is there a better way to do this ? I tried DataTable1.Clear() but that does not generates delete statements when doing adapter.Update(DataTable1);

If you want to mark all rows deleted, why dont you use a plain foreach -loop?

foreach(DataRow row in DataTable1.Rows) row.Delete();

Delete will mark this row as Deleted which is important for DataAdapters, they will call their DeleteCommand to delete this row from the database. But it will not remove the row from the DataTable immediately. If you want to remove it from the table use DataTable.Rows.RemoveAt(index) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM