Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting row from datatable in C#

Tags:

c#

datatable

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?

like image 383
Norman Avatar asked Jun 17 '11 19:06

Norman


People also ask

How to Delete a row from a 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.

Can we update DataTable in C#?

use SetModified() method to update data table value.


3 Answers

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

like image 184
IAmTimCorey Avatar answered Oct 06 '22 14:10

IAmTimCorey


Try using Delete method:

    DataRow[] drr = dt.Select("Student=' " + id + " ' "); 
    for (int i = 0; i < drr.Length; i++)
        drr[i].Delete();
    dt.AcceptChanges();
like image 32
manji Avatar answered Oct 06 '22 12:10

manji


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); 
} 
like image 22
Wicked Coder Avatar answered Oct 06 '22 12:10

Wicked Coder