Difference between two Datasets

Description :

Using below function we can find the difference of two dataset and store into third dataset.
Inside function we are passing first dataset table as first parameter and second dataset
table as second parameter and returns third table that we can store in third dataset

public static DataTable Difference(DataTable First, DataTable Second)

//Create Empty Table
DataTable table = new DataTable();
//Must use a Dataset to make use of a DataRelation object
using (DataSet dsScr3 = new DataSet())
//Add tables
dsScr3.Tables.AddRange(new DataTable[] { First.Copy(), Second.Copy() });
//Get Columns for DataRelation
DataColumn[] firstcolumns = new DataColumn[dsScr3.Tables[0].Columns.Count];
for (int i = 0; i < firstcolumns.Length; i++)
firstcolumns[i] = dsScr3.Tables[0].Columns[i];
DataColumn[] secondcolumns = new DataColumn[dsScr3.Tables[1].Columns.Count];
for (int i = 0; i < secondcolumns.Length; i++)
secondcolumns[i] = dsScr3.Tables[1].Columns[i];

//Create DataRelation

DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);
//Create columns for return table
for (int i = 0; i < First.Columns.Count; i++)
table.Columns.Add(First.Columns[i].ColumnName, First.Columns[i].DataType);

//If First Row not in Second, Add to return table.

foreach (DataRow parentrow in dsScr3.Tables[0].Rows)
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
return table;


Guest Author: David Hughes22 Oct 2012

This doesn't show added data rows, so I turned the tables round to get the added rows (but of course now it doesn't get the deleted rows) Any ideas?

Also did you manage to figure out how to highlight the changed data cell?

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: