I'll bet you've looked at DataTable.Merge or DataTable.GetChanges and
thought they might work - I have.
But they won't work in your case. In ADO's eyes no data has changed.
They only work with changes since the data was loaded or since
AcceptChanges was called.
DataTable table1 = new DataTable();
table1.Columns.Add("ID", typeof(int));
table1.Columns.Add("Name", typeof(string));
table1.Columns.Add("Age", typeof(int));
table1.PrimaryKey = new DataColumn[] { table1.Columns["ID"]};
table1.Rows.Add(new object[] { 1, "Jason", 10 });
table1.Rows.Add(new object[] { 2, "Bob", 22 });
table1.Rows.Add(new object[] { 3, "Tim", 28 });
table1.AcceptChanges();
DataTable modifiedTable = table1.Copy();
modifiedTable.Rows[0]["Age"] = 40;
modifiedTable.Rows[0]["Name"] = Convert.DBNull;
modifiedTable.Rows.Add(new object[] { 4, "New Person", 30 });
DataTable changedData1 = modifiedTable.GetChanges(); // Will hold 2
records
modifiedTable.AcceptChanges();
DataTable changedData2 = modifiedTable.GetChanges(); // Will be null -
I called AcceptChanges
DataTable table1Copy = table1.Copy();
table1Copy.Merge(modifiedTable); // Will store all
resulting updated and adds - 4 records
You're going to have to do the comparison work yourself by looping
though each record and looking for changes:
foreach (DataRow row in modifiedTable.Rows)
{
//ID is the PrimaryKey so we can use that with Find - null means
it's new
DataRow existingRow = table1.Rows.Find(row["ID"]);
if (existingRow == null)
{
Console.WriteLine("ID " + row["ID"] + " is new");
}
else
{
// Now compare each column and break it there's a difference
foreach (DataColumn column in table1.Columns)
{
if (String.Compare(row[column.ColumnName] as string,
existingRow[column.ColumnName] as string, true) != 0)
{
Console.WriteLine("ID " + row["ID"] + " has changed
data - " + column.ColumnName);
break;
}
}
}
}
How can I reconcile changes between two data table and create a subset of
those changes. I have two data tables with same schema which gets populated
from two different xml files. I want to get hold of missing & changed rows in
first table from second table. Tables have ID as primary key.
Thanks