Explanation of HasChanges() Method in C#
The HasChanges() method in C# is a convenient method provided by the DataSet class. It is used to determine whether any changes have been made to the data within the DataSet since the last time the DataSet was loaded or since the last call to AcceptChanges() method. This method is particularly useful when you need to check whether any modifications have been made to the data before deciding to save those changes to a database or take any other action.
Here's an explanation of the HasChanges() method along with a complete source code example and the expected output:
Explanation of HasChanges() Method:
The HasChanges() method returns a Boolean value - true if there are changes detected in the DataSet, and false if there are no changes. These changes can include added, modified, or deleted rows in any of the DataTable objects contained within the DataSet. It provides a simple way to check if there are pending changes before deciding whether to take further actions, such as saving the data to a database.
Source Code Example (Using HasChanges() Method):
Let's illustrate the use of the HasChanges() method with a C# source code example:
using System;
using System.Data;
class Program
{
    static void Main()
    {
        // Create a new DataSet
        DataSet dataSet = new DataSet();
        // Create a DataTable
        DataTable employeeTable = new DataTable("Employees");
        // Define columns for the DataTable
        employeeTable.Columns.Add("EmployeeID", typeof(int));
        employeeTable.Columns.Add("FirstName", typeof(string));
        employeeTable.Columns.Add("LastName", typeof(string));
        // Add the DataTable to the DataSet
        dataSet.Tables.Add(employeeTable);
        // Add a new row to the DataTable
        DataRow newRow = employeeTable.NewRow();
        newRow["EmployeeID"] = 101;
        newRow["FirstName"] = "John";
        newRow["LastName"] = "Doe";
        employeeTable.Rows.Add(newRow);
        // Check if there are changes in the DataSet
        bool hasChanges = dataSet.HasChanges();
        Console.WriteLine("Are there changes in the DataSet? " + hasChanges);
        // Modify an existing row
        employeeTable.Rows[0]["LastName"] = "Smith";
        // Check again if there are changes
        hasChanges = dataSet.HasChanges();
        Console.WriteLine("Are there changes in the DataSet after modification? " + hasChanges);
    }
}
Expected Output:
Are there changes in the DataSet? True
Are there changes in the DataSet after modification? True
In this example, we create a DataSet containing a DataTable with one row of data. Initially, the HasChanges() method returns true because we added a new row. After modifying an existing row, the method still returns true because changes have been made to the data. This demonstrates how to use HasChanges() to check for pending changes in a DataSet.