VB.NET 无法从现有数据集 Table 向数据 Table 添加或导入行

VB.NET Unable to add or import rows to a DataTable from a existing DataSet Table

我在以下代码中遇到问题,在 dt.ImportRow(cr) 行出现“对象未设置为对象的实例”错误。

Dim DataGrid As DataTable = Me.DataSet1.MyGrid()

    For i As Integer = DataGrid.Rows.Count - 1 To -0 Step -1
        Dim dr As DataRow = DataGrid.Rows.Item(i)
        Dim new_value1 = 0
        Dim new_value2 = 0
        Dim new_value3 = 0
        Dim new_value4 = 0
        Dim new_value5 = 0

        If CheckItem(dr("WH"), dr("PC")) Then
            Dim dt As DataTable 
            For Each cr As DataRow In Me.DataSet1.MyGrid()
                If cr("parent") = dr("WH") + dr("PC") And cr("lev") = dr("lev") + 1 Then
                    dt.ImportRow(cr)

                End If
            Next
            dt.AcceptChanges()

            RemoveDuplicateRows(dt)

            For Each dr1 As DataRow In dt.Rows
                new_value1 = new_value1 + dr1("new_value1")
                new_value2 = new_value2 + dr1("new_value2")
                new_value3 = new_value3 + dr1("new_value3")
                new_value4 = new_value4 + dr1("new_value4")
                new_value5 = new_value5 + dr1("new_value1") + dr1("new_value2") + dr1("new_value3") + dr1("new_value4")
            Next

            dr("new_value1 ") = Math.Round(new_value1 , 4)
            dr("new_value2 ") = Math.Round(new_value2 , 4)
            dr("new_value3 ") = Math.Round(new_value3 , 4)
            dr("new_value4 ") = Math.Round(new_value4 , 4)
            dr("new_value5 ") = Math.Round(new_value5 , 4)
        End If

    Next

我想做的是用 Me.DataSet1.MyGrid() 中可以重复的行填充 dt,这样我就可以执行 RemoveDuplicateRows() 方法来只显示不同的行,然后将它们的值相加。问题是我有重复的值,当我对值进行累加时,结果是重复的,例如我期望 4 我得到 8.

为什么我无法 Rows.Add(cr)ImportRow(cr) 进入 dt 数据表?

您所在的行:

Dim dt As DataTable

需要扩展一点为:

Dim dt As DataTable = DataGrid.Clone()

这将导致新数据表 dt 具有与原始数据表相同的列 DataGrid