开发者

DataTable.GetChanges() keeps returning NULL

开发者 https://www.devze.com 2022-12-11 02:45 出处:网络
I am trying to get all the rows that exist in allData but not in removeData public static DataTable RemoveDuplicateRows(DataTable allData,

I am trying to get all the rows that exist in allData but not in removeData

public static DataTable RemoveDuplicateRows(DataTable allData, 
    DataTable removeData) 
{
    removeData.Merge(allData);
    DataTable newData = removeData.GetChanges(); 
    removeData.RejectChanges();
    return newData;
}

removeData is empty prior to the call in this case (just a new DataTable();)

But newData always has a value of null after the DataTable newData = removeData.GetChanges(); line

Final Solution:

    public static DataTable RemoveDuplicateRows(DataTable allData, DataTable removeData) 
    {
        DataTable dupli开发者_如何学运维cate = allData.Clone();
        foreach (DataRow row in allData.Rows)
        {
            duplicate.ImportRow(row);
        }
        foreach (DataRow row in duplicate.Rows)
        {
            row.SetAdded();
        } 

        removeData.Merge(duplicate);
        DataTable newData = removeData.GetChanges(DataRowState.Added);
        removeData.RejectChanges();
        allData.RejectChanges();
        return newData;
    }


The DataTable.GetChanges() method is dependent on the DataRow.RowState property. For each row in a pair of DataTables, a DataTable.Merge() will either preserve their 'RowState' property, or reset it to 'Unchanged' (depending on the overload that you choose to use). This means that when you merge two DataTables with rows that have 'Unchanged' RowStates, the merged table will also contain 'Unchanged' rows and the DataTable.GetChanges method will return null or Nothing.


Your removeData DataTable needs to have the same columns/fields as allData. In other words, it can't just be a new DataTable().

0

精彩评论

暂无评论...
验证码 换一张
取 消