【问题标题】:DataTable.NewRow - Combine DataRow Object and String From AnotherDataTable.NewRow - 合并另一个 DataRow 对象和字符串
【发布时间】:2018-11-28 21:58:59
【问题描述】:

有没有一种方法可以让我使用现有的 DataRow 加上一个额外的字符串来创建一个新对象以作为新行插入到数据表中?

本质上,我克隆了一个数据表,然后在此数据表中添加了另外 2 列,并希望使用克隆它的原始表中的数据以及在这种情况下分配给谁的附加信息来更新克隆的数据表以及在什么日期。

我尝试了以下尝试在结果中使用 'r' DataRow 创建一个新对象,然后另外添加了 2 个字符串,但是我收到了一个错误。

Private Shared Sub PopulatedCurrAssigned

    _currAssigneddt = Config.MasterTbl.Clone()
    _currAssigneddt.Columns.Add("Assigned Date", GetType(DateTime))
    _currAssigneddt.Columns.Add("Assigned To", GetType(String))
    Dim MasterTbl As DataTable = config.MasterTbl
    Dim actiontbl as DataTable = config.RefreshMasterActionTbl()

    For Each row In MasterTbl.Rows

        Dim result() as DataRow = actiontbl.Select("FreshAppsID = '" & row("FreshAppsID") & "'")

        If result.Count() > 0 Then
            For each r as DataRow in result
                _currAssigneddt.Rows.Add(New Object() {r, "New", "New"})
            Next
        End If
    Next

End Sub

非常感谢任何建议或帮助。

更新

尝试了 Rango 的以下建议,结果如下:

System.ArgumentException
HResult=0x80070057
Message=Unable to cast object of type 'System.Object[]' to type 
'System.IConvertible'.Couldn't store <System.Object[]> in Ledger Date Column.  
Expected type is DateTime.
 Source=System.Data

Inner Exception 1:
InvalidCastException: Unable to cast object of type 'System.Object[]' to type 
'System.IConvertible'.

更新 2

我的错误是我从变量中删除了作为 DataRow 的声明。

我重新添加了这个,它纠正了问题。

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    可以使用:

    _currAssigneddt.Rows.Add(r.ItemArray.Concat({Date.Now, "Name of Person"}).ToArray())
    

    虽然这不是很有效,但我更喜欢(在您的示例中修复类型问题):

    Dim newRow = _currAssigneddt.Rows.Add(r.ItemArray)
    newRow("Assigned Date") = Date.Now
    newRow("Assigned To") = "Name of Person"
    

    这更易读,类型安全,并且不依赖于(新)列的索引。

    【讨论】:

    • @Lynchie:由于您的样本数据错误,您会收到此错误。添加一个 DateTime 列,然后尝试分配 "New"。我已经编辑了我的答案
    猜你喜欢
    • 1970-01-01
    • 2019-05-22
    • 2023-03-13
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多