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

时间:2016-01-23 18:26:28

标签: vb.net datatable datarow

我已经加入了一个较旧的项目vb.net项目。我正在尝试查询数据表并将生成的DataRow导入到新创建的DataTable中。

代码:

    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循环中的“对象未设置为对象的实例”错误。我已经尝试手动创建表中的数据列,但这也会导致相同的错误。

1 个答案:

答案 0 :(得分:0)

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

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