Tuesday, June 19, 2012

DataTable RejectChanges


The DataTable’s RejectChanges() method rolls back the changes done to the DataRow.

Now let us see with an example, on how the rowstate property gets affected by calling the RejectChanges() method of the DataTable.

Let us add a new row to a DataTable, and perform various operations on the row to observer the change in the RowState of the row.

// Fill the DataTable with your own logic
// Here we will fill the table by calling the Domain class.
clsEmployee objEmp = new clsEmployee();
DataTable dtEmployee = objEmp.GetEmployeeList();
DataRow drEmp;
//
// Add a new Row and perform data changes
drEmp = dtEmployee.NewRow(); // RowState - Detached
dtEmployee.Rows.Add(drEmp);  // RowState - Added
dtEmployee.RejectChanges();  // RowState - Detached
drEmp["ID"] = 3134;          // RowState - Detached
drEmp.Delete();              // RowState - Detached

drEmp = dtEmployee.NewRow(); // RowState - Detached
dtEmployee.Rows.Add(drEmp);  // RowState - Added
dtEmployee.AcceptChanges();  // RowState - Unchanged
drEmp["ID"] = 3134;          // RowState - Modified
dtEmployee.RejectChanges();  // RowState - Unchanged

drEmp = dtEmployee.NewRow(); // RowState - Detached
dtEmployee.Rows.Add(drEmp);  // RowState - Added
dtEmployee.AcceptChanges();  // RowState - Unchanged
drEmp["ID"] = 3134;          // RowState - Modified
dtEmployee.AcceptChanges();  // RowState - Unchanged
drEmp.Delete();              // RowState - Deleted
dtEmployee.RejectChanges();  // RowState - Unchanged

Calling
RejectChanges, after Adding a new row removes the row from the DataTable
Calling RejectChanges, after Modifying a row rolls back the state of the row to Unchanged
Calling
RejectChanges, after Deleting a row rolls back the state of the row to Unchanged

Notice that, every time you call the DataTable’s RejectChanges() method, the changes are rolled back either to the initial state or to the state when AcceptChanges() was last called on the DataTable.

The following are the changes of RowState of the DataRows in the DataTable, before and after calling the DataTable’s AcceptChanges() method.

RowState before calling RejectChanges()
RowState after calling RejectChanges()
Impact on the Row
Added

Detached
Row is Permanently Removed from the DataTable
Modified

Unchanged
Data modifications to the row are rolled back.
Deleted
Unchanged
Row is retained in the DataTable


The RejectChange() method can also be called on the individual DataRows in the DataTable, calling the DataTable’s RejectChanges() method, will rollback the changes of all the DataRows in the DataTable.


Search Flipkart Products:
Flipkart.com

No comments: