Understanding the RejectChanges() Method in ADO.NET with C#
In C#, the RejectChanges()
method is an important feature of the DataTable
class in ADO.NET. It is used to cancel any changes made to the rows within a DataTable and restore their original values from when it was first loaded or when the last call to AcceptChanges()
was made. This method is particularly useful when you want to discard changes made to a DataTable without affecting the corresponding data in the database.
The primary purpose of RejectChanges()
is to roll back changes made to a DataTable and its rows to their previous state, effectively canceling any pending modifications.
Illustration with Complete Source Code
Let's illustrate how to use the RejectChanges()
method with a complete C# source code example:
using System;
using System.Data;
class Program
{
static void Main()
{
// Create a DataTable with some sample data
DataTable dataTable = new DataTable("Employee");
dataTable.Columns.Add("EmployeeID", typeof(int));
dataTable.Columns.Add("FirstName", typeof(string));
dataTable.Columns.Add("LastName", typeof(string));
// Add a new row to the DataTable
DataRow newRow = dataTable.NewRow();
newRow["EmployeeID"] = 1;
newRow["FirstName"] = "John";
newRow["LastName"] = "Doe";
dataTable.Rows.Add(newRow);
// Modify the data in the DataRow
newRow["FirstName"] = "Jane";
newRow["LastName"] = "Smith";
Console.WriteLine("Original Data:");
PrintDataTable(dataTable);
// Reject the changes and restore the original values
dataTable.RejectChanges();
Console.WriteLine("\nAfter Rejecting Changes:");
PrintDataTable(dataTable);
}
static void PrintDataTable(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
Console.WriteLine($"{row["EmployeeID"]}, {row["FirstName"]}, {row["LastName"]}");
}
}
}
In this example:
- We create a
DataTable
named "Employee" with columns for EmployeeID, FirstName, and LastName.
- A new DataRow (
newRow
) is added to the DataTable with initial values.
- We then modify the FirstName and LastName values of the DataRow.
- The original data is printed before and after rejecting changes using the
RejectChanges()
method.
Expected Output
After executing the code, the output will demonstrate how the RejectChanges()
method restores the DataTable and its rows to their original state:
Original Data:
1, John, Doe
After Rejecting Changes:
1, John, Doe
As you can see, after calling RejectChanges()
on the DataTable
, the modifications made to the DataRow are undone, and the data is reverted to its original values. This is a useful feature when working with DataTables that you want to temporarily modify but may need to discard those changes later.