Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datatable

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);

like image 409
GuidoG Avatar asked Dec 03 '25 23:12

GuidoG


1 Answers

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).

like image 172
Tim Schmelter Avatar answered Dec 05 '25 14:12

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!