Compare the two datatable contents to see if they are the same

  • 2020-06-03 08:11:58
  • OfStack

DataTable can use RowStatus to tell if a state has changed. But there are times when we want the row status to be Modified without indicating a change in content, and we may need to write our own methods to determine that. For example, if the state of a selected column in DataTable has changed, I do not want the system to determine that the row state of DataTable has changed and update the data back to the database.
This allows us to save when we need to determine which columns in DataTable have changed. Here is how to compare the contents of the two DataTable to see if they are the same:


 ///   <summary> 
///    Compare the two DataTable If content is equal, first compare quantity, equal quantity compare content  
///   </summary> 
///   <param   name= "dtA "> </param> 
///   <param   name= "dtB "> </param> 
private bool CompareDataTable(DataTable dtA, DataTable dtB)
{
    if (dtA.Rows.Count == dtB.Rows.Count)
    {
if (CompareColumn(dtA.Columns, dtB.Columns))
{
    // Than the content  
    for (int i = 0; i < dtA.Rows.Count; i++)
    {
for (int j = 0; j < dtA.Columns.Count; j++)
{
    if (!dtA.Rows[i][j].Equals(dtB.Rows[i][j]))
    {
return false;
    }
}
    }
    return true;
}
else
{
    return false;
}
    }
    else
    {
return false;
    }
}
///   <summary> 
///    Compare the names of two sets of fields , The data type 1 to  
///   </summary> 
///   <param   name= "dcA "> </param> 
///   <param   name= "dcB "> </param> 
///   <returns> </returns> 
private bool CompareColumn(System.Data.DataColumnCollection dcA, System.Data.DataColumnCollection dcB)
{
    if (dcA.Count == dcB.Count)
    {
foreach (DataColumn dc in dcA)
{
    // Look for the same field name  
    if (dcB.IndexOf(dc.ColumnName) > -1)
    {
// Test data type  
if (dc.DataType != dcB[dcB.IndexOf(dc.ColumnName)].DataType)
{
    return false;
}
    }
    else
    {
return false;
    }
}
return true;
    }
    else
    {
return false;
    }
}


Related articles: