To understand AcceptChanges() and RejectChanges() methods better, we need to understand Row States and Row Versions. Every DataRow that is present in DataTable of a DataSet has RowState property. Following are the different Row State
1. Unchanged :- When we call DataAdapter.Fill() method, data is loaded into the DataSet and the RowState of all the rows will be Unchanged.
2. Modified :- When we edit a row the row state becomes Modified.
3. Deleted:- If we delete a row, the row state becomes Deleted.
At this point If we invoke, DataAdapter.Update() method, based on the RowState, respective INSERT, UPDATE and DELETE commands are executed against the underlying database table and AcceptChanges() is called automatically.
When AcceptChanges() is invoked RowState property of each DataRow changes. Added and Modified rows become Unchanged, and Deleted rows are removed. It means for Dataset it is as if nothing has happened since it was last loaded , so no change will be committed to database on calling update method.
When RejectChanges() is invoked RowState property of each DataRow changes. Added rows are removed. Modified and Deleted rows becomes Unchanged. Thus, It Rejects all changes made to the DataSet since the last time it was loaded or since the last time AcceptChanges() was called.
Both AcceptChanges() and RejectChanges() methods can be invoked at the following levels
1. At the DataSet level - When invoked at the DataSet level, they get called automatically on each DataTable with in the DataSet, and on each DataRow within each DataTable.
2. At the DataTable level - When invoked at the DataTable level, they get called automatically on each DataRow within each DataTable.
3. At the DataRow level - Gets called only for the row, on which it is invoked.
DataSet ds = new DataSet(); // create a table with a single column DataTable dt = ds.Tables.Add(); dt.Columns.Add("MyColumn", typeof(System.Int32)); DataRow row; row = dt.NewRow(); row["MyColumn"] = 1; dt.Rows.Add(row); // RowState = Added ds.AcceptChanges(); // RowState = Unchanged row["MyColumn"] = 2; // RowState = Modified ds.RejectChanges(); // RowState = Unchanged, row["MyColumn"] = 1 row.Delete(); // RowState = Deleted ds.RejectChanges(); // RowState = Unchanged // The row isn't removed from the DataTable.
Don't get confused with AcceptChanges() and RejectChanges() method , For the database perspective both are same , meaning if we call AcceptChanges() method , Row State becomes unchanged , so data adapter doesn't fire any Sql command on database as a result nothing gets commit to database .
when we use RejectChanges() method then all changes made to DataSet since it was last loaded , rolls back , so the dataset comes to its previous state , at this moment when we call dataAdapter's Update()method , Nothing is going to change on Database.