Home > database >  Copy row from dataTable to datarow and then to another dataTablein vb.net
Copy row from dataTable to datarow and then to another dataTablein vb.net

Time:01-20

How to transfer a row in dataTable to a datarow and then pass the datarow to a new dataTable

Public function fn_transfer(dt as dataTable) 

Dim dtNew as new dataTable

dtNew = dt.Clone()

For i as integer= 0 to dt.rows.count -1 

If dt.rows(i)("name").ToString.trim = "" or 
dt.rows(i)("street").ToString.trim = "" then

Dim dr() as new datarow
For each dr in dt.rows(i)
dr = dt.Rows(i).Itemarray

Next


dtNew.importrow(dr(0))

Next

This code is not working. Kindly rectify the code.

CodePudding user response:

So you want to import only those rows which Name or Street is empty?

If you want to use a loop this should work:

For Each r As DataRow in dt.rows
    If String.IsNullOrEmpty(r.Field(Of String)("Name")) OrElse String.IsNullOrEmpty(r.Field(Of String)("Steet"))
      dtNew.importrow(row)          
    End If
Next

Another way is to use LINQ and CopyToDataTable:

Dim dtNew as DataTable = dt.Clone() ' empty table with same columns
Dim filteredRows = dt.AsEnumerable().
    Where(Function(r) String.IsNullOrEmpty(r.Field(Of String)("Name")) OrElse String.IsNullOrEmpty(r.Field(Of String)("Steet"))).
    ToList()

If filteredRows.Any() Then dtNew = filteredRows.CopyToDataTable()
  •  Tags:  
  • Related