Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple rows in a DataTable?

How can I delete specific DataRows within a loop of a DataTable rows which meet a custom condition -lets say the rows having an index of even number-? (Without using LINQ)

Thanks

like image 843
pencilCake Avatar asked May 26 '10 13:05

pencilCake


People also ask

How to delete multiple rows from DataTable in vb net?

ForEach( row => row. Delete() ); dt. EndLoadData(); dt. AcceptChanges();

How to remove Data from DataTable?

There are two methods you can use to delete a DataRow object from a DataTable object: the Remove method of the DataRowCollection object, and the Delete method of the DataRow object. Whereas the Remove method deletes a DataRow from the DataRowCollection, the Delete method only marks the row for deletion.


2 Answers

It depends on what you mean by 'delete'.

If you mean mark them as deleted, just call the Delete() method on each row as you visit it in your loop. You then need to call AcceptChanges() on the data table to finalize the delete - presumably after you update your database (if one is involved).

foreach( DataRow row in someTable.Rows ) {     if( /* your condition here */ )         row.Delete(); } someTable.AcceptChanges(); 

If you mean remove it from the DataTable, then you need to do so in two passes:

List<DataRow> rowsToDelete = new List<DataRow>(); foreach( DataRow row in someTable.Rows ) {     if( /* your condition here */ )     {         rowsToDelete.Add( row );     } }  foreach( DataRow row in rowsToDelete ) {     someTable.Rows.Remove( row ); } 

It's worth pointing out that you can always use the first method to remove rows - since marking rows as Deleted and then accepting changes will automatically remove them from the table. But, sometimes it is more clear and efficient to simply remove the DataRow objects from the Rows collection.

like image 183
LBushkin Avatar answered Sep 19 '22 11:09

LBushkin


Try something like this example

DataTable table = new DataTable(); table.Columns.Add("Foo",typeof(int)); for (int i = 0; i < 10; i++)     table.Rows.Add(i);  for (int i = table.Rows.Count -1; i >=0; i--) {     // sample removes all even foos     if ((int)table.Rows[i]["Foo"] % 2 == 0)         table.Rows.RemoveAt(i); } 
like image 37
Anthony Pegram Avatar answered Sep 19 '22 11:09

Anthony Pegram