DataTable.NewRow - Combine DataRow Object and String From Another

0

Is there a way I can essentially create a New Object to insert as a New Row in a Datatable using the existing DataRow plus an additional string?

Essentially I clone a Datatable but then add another 2 columns in to this Datatable and wish to update the cloned datatable with both the data from the original table from which it was cloned, plus additional information in this case who it was Assigned To and on what date.

I tried the following attempting to create a New Object using 'r' the DataRow in result and then additionally added 2 strings, however I receive an error.

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

Any suggestions or assistance is greatly appreciated.

Update

Tried the below suggestion from Rango and got the following:

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'.

Update 2

My mistake for the error I had removed the declaration out of the variable as a DataRow.

I added this back in and it rectified the problem.

vb.net
asked on Stack Overflow Nov 28, 2018 by Lynchie • edited Nov 28, 2018 by Lynchie

1 Answer

1

You could use:

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

Although this is not very efficient, i'd prefer (fixing also the type issue in your example):

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

This is much better readable, type safe and doesn't rely on indexes of the (new) columns.

answered on Stack Overflow Nov 28, 2018 by Tim Schmelter • edited Nov 28, 2018 by Tim Schmelter

User contributions licensed under CC BY-SA 3.0