简体   繁体   English

如何减去两个数据表?

[英]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. 当我单击Button1时,它将把当前数据放入firstDsData中。 A few seconds later when i click Button2, it will upload the current data to the secondDsData and merge it together. 几秒钟后,当我单击Button2时,它将把当前数据上传到secondDsData并将其合并在一起。 Then they will merge together into FinalDsData. 然后它们将合并到FinalDsData中。 Differences datatable will get the changes from finaldsdata. 差异数据表将从finaldsdata获得更改。

The problem is in the last section. 问题在最后一部分。 FinalDsData.GetChanges() doesn't work. FinalDsData.GetChanges()不起作用。 It says nullreferenceexception. 它说nullreferenceexception。 I also tried get changes with RowState.Unchanged/Modified(). 我还尝试使用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: 如果您的唯一目标是在网格上显示更改,则可以使用LINQ查找两个表之间的差异,例如:

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? 如果需要输出DataTable表,则可以将LINQ结果转换为DataTable ,请参见将新数据转换为数据表?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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