Share via


Deleting a Row from a Table

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. While the Remove method deletes a DataRow from the DataRowCollection, the Delete method only marks the row for deletion. The actual removal occurs when the application calls the AcceptChanges method. By using Delete, you can programmatically check which rows are marked for deletion before actually removing them. When a row is marked for deletion, its RowState property is set to Deleted.

When using a DataSet or DataTable in conjunction with a DataAdapter and a relational data source, use the Delete method of the DataRow to remove the row. The Delete method marks the row as Deleted in the DataSet or DataTable but does not remove it. Instead, when the DataAdapter encounters a row marked as Deleted, it executes its DeleteCommand to delete the row at the data source. The row can then be permanently removed using the AcceptChanges method. If you use Remove to delete the row, the row will be removed entirely from the table but the DataAdapter will not delete the row at the data source.

The Remove method of the DataRowCollection takes a DataRow as an argument and removes it from the collection, as shown in the following example.

workTable.Rows.Remove(workRow)
[C#]
workTable.Rows.Remove(workRow);

In contrast, the following example demonstrates how call the Delete method on a DataRow to change its RowState to Deleted.

workRow.Delete
[C#]
workRow.Delete();

If a row is marked for deletion and you call the AcceptChanges method of the DataTable object, the row is removed from the DataTable. In contrast, if you call RejectChanges, the RowState of the row reverts to what it was before being marked as Deleted.

**Note   **If the RowState of a DataRow is Added, meaning it has just been added to the table, and it is then marked as Deleted, it is removed from the table.

See Also

Manipulating Data in a DataTable | DataRow Class | DataRowCollection Class | DataTable Class