9.3 Deleting Rows

The Delete( ) method deletes rows from the DataTable . If the RowState is Added , the row is removed; otherwise the RowState of the existing DataRow is changed to Deleted . The row is permanently removed from the table only when AcceptChanges( ) is called on the row either explicitly or implicitly when the Update( ) method of the DataAdapter successfully updates the changes to the row back to the data source.

 // delete the first row from the table DataRow row = dt.Rows[0]; row.Delete();        // RowState changed to Deleted row = dt.NewRow(); // ... code to set the data for the row // add the row to the table dt.Rows.Add(row); // delete the row row.Delete();        // Newly inserted row is removed from the table 

When you iterate through the rows of a DataTable , it is important to remember that rows are only marked for deletion and are still present in the collection of rows for the table. If you might be accessing Deleted rows in the DataTable , you need to explicitly check the state of the row and ignore it if it is Deleted . This is shown in the following example:

 // Iterate over the results (and ignore deleted rows). foreach (DataRow dr in ds.Tables["Customers"].Rows) {     if (dr.RowState != DataRowState.Deleted)     {         // ... process the row     } } 

If you try to access the current value of a field in a row that has been deleted, you'll receive the RowNotInTableException or DeleteRowInacessibleException .

ADO. NET in a Nutshell
ADO.NET in a Nutshell
ISBN: 0596003617
EAN: 2147483647
Year: 2005
Pages: 415

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net