I'm having a problem deleting rows from a datatable. In my program, I am reading info from a database into a datatable using an sql query. I use an oledb connection and the code dt.Load(command.ExecuteReader());
to do this. Later, I want to delete rows that match an id string. I have tried the following code buy cannot get it to work:
DataRow[] drr = dt.Select("Student=' " + id + " ' ");
for (int i = 0; i < drr.Length; i++)
dt.Rows.Remove(drr[i]);
dt.AcceptChanges();
Can anyone please suggest another way with an example?
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.
use SetModified() method to update data table value.
This question will give you good insights on how to delete a record from a DataTable:
DataTable, How to conditionally delete rows
It would look like this:
DataRow[] drr = dt.Select("Student=' " + id + " ' ");
foreach (var row in drr)
row.Delete();
Don't forget that if you want to update your database, you are going to need to call the Update command. For more information on that, see this link:
http://www.codeguru.com/forum/showthread.php?t=471027
Try using Delete method:
DataRow[] drr = dt.Select("Student=' " + id + " ' ");
for (int i = 0; i < drr.Length; i++)
drr[i].Delete();
dt.AcceptChanges();
There several different ways to do it. But You can use the following approach:
List<DataRow> RowsToDelete = new List<DataRow>();
for (int i = 0; i < drr.Length; i++)
{
if(condition to delete the row)
{
RowsToDelete.Add(drr[i]);
}
}
foreach(var dr in RowsToDelete)
{
drr.Rows.Remove(dr);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With