简体   繁体   中英

how to subtract two datatables?

I want to subtract two datatables. What i want is that in below Image.

这是图像

I have the following code and i stacked at last point. Here is what i want to do in the code.

When i click Button1, it will get current data into firstDsData. A few seconds later when i click Button2, it will upload the current data to the secondDsData and merge it together. Then they will merge together into FinalDsData. Differences datatable will get the changes from finaldsdata.

The problem is in the last section. FinalDsData.GetChanges() doesn't work. It says nullreferenceexception. I also tried get changes with RowState.Unchanged/Modified(). They also didn't work.

    DataTable firstDsData = new DataTable();
    DataTable secondDsData = new DataTable();
    DataTable finalDsData = new DataTable();
    DataTable DifferenceDataTable = new DataTable();

    private void Form1_Load(object sender, EventArgs e)
    {
        this.dataTable1TableAdapter.Fill(this.dataWE.DataTable1);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        firstDsData = dataTable1TableAdapter.GetData();

    }

    private void button2_Click(object sender, EventArgs e)
    {
        secondDsData = dataTable1TableAdapter.GetData();

        finalDsData.Merge(firstDsData);
        finalDsData.AcceptChanges();
        finalDsData.Merge(secondDsData); //Until here i can get data into finalDsData. No Problem.
        DifferenceDataTable = finalDsData.GetChanges(); // Problem in here.Nullreferenceexception
        ultraGrid2.SetDataBinding(DifferenceDataTable, DifferenceDataTable.TableName);
    }

If your only goal is to show changes on a grid then you can use LINQ to find difference between two tables like:

var changes = (from dr1 in firstDsData.AsEnumerable()
    from dr2 in secondDsData.AsEnumerable()
    where dr1.Field<string>("Name") == dr2.Field<string>("Name")
    select new
    {
        Name = dr1.Field<string>("Name"),
        Value = dr1.Field<decimal>("Value") - dr2.Field<decimal>("Value")
    }).ToList();

To show it to your grid you can do:

ultraGrid2.DataSource = changes;

If you want a DataTable for the output then you can convert your LINQ results to a DataTable , see Convert select new to DataTable?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM