将 DataRow 导入新的 DataTable 会导致错误。 VB.NET

Importing a DataRow to a new DataTable results in error. VB.NET

我被分配到一个较旧的项目 vb.net 项目中。我正在尝试查询数据 table 并将生成的数据行导入到新创建的数据表中。

代码:

    Private Sub FilterSelectedByString(ByVal str As String, ByVal mID As Integer)
        Try
            dsTargetEmployees = MemberShipManager.GetMessageTargets(_page.Client, mID)
            dtTargets = dsTargets.Tables("MessageTargets")
            Dim dt As DataTable = Nothing
            For Each dr As DataRow In dtTargets.Select(str)
                dt.ImportRow(dr)
            Next
            lstSelected.Items.Clear()
            lstSelected.DataSource = dt
            lstSelected.DataTextField = "EmployeeName"
            lstSelected.DataValueField = "EmployeeID"
            lstSelected.DataBind()
        Catch ex As Exception
           //error code
        End Try
    End Sub

这会导致 for 循环中出现 "object not set to an instance of an object" 错误。我尝试在 table 中手动创建数据列,但这也会导致同样的错误。

解决了我自己的问题。将原始 table 复制到创建的 table 然后清除它构建了正确的结构。

Private Sub FilterSelectedByString(ByVal str As String, ByVal mID As Integer)
    Try
        dsTargetEmployees = MemberShipManager.GetMessageTargets(_page.Client, mID)
        dtTargets = dsTargets.Tables("MessageTargets")
        Dim dt As DataTable = dtTargets.Copy()
        dt.Clear()
        For Each dr As DataRow In dtTargets.Select(str)
            dt.ImportRow(dr)
        Next
        lstSelected.Items.Clear()
        lstSelected.DataSource = dt
        lstSelected.DataTextField = "EmployeeName"
        lstSelected.DataValueField = "EmployeeID"
        lstSelected.DataBind()
    Catch ex As Exception
       //error code
    End Try
End Sub