Simple Way to Copy or Clone a Datarow

Simple way to copy or clone a DataRow?

You can use ImportRow method to copy Row from DataTable to DataTable with the same schema:

var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);

Update:

With your new Edit, I believe:

var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];

will work

Clone/Copy, Edit then Add Dataset Row

If you want to copy a whole row from a previous one this is a possible way

// Row to copy from
DataRow dr = JoblistDataSet.Tables["Joblist"].Rows[rowIndex];

// Row that receives the values from source
DataRow newrow = JoblistDataSet.Tables["Joblist"].NewRow();

// Copy the ItemArray of the source row to the destination row
// Note that this is not a reference copy.
// Internally a new object array is created when you _get_ the ItemArray
newrow.ItemArray = dr.ItemArray;

// Change whateever you need to change
newrow[0] = 99;

// Add the new row into the datatable collection
JoblistDataSet.Tables["Joblist"].Rows.Add(newrow);

Copy rows from one Datatable to another DataTable?

foreach (DataRow dr in dataTable1.Rows) {
if (/* some condition */)
dataTable2.Rows.Add(dr.ItemArray);
}

The above example assumes that dataTable1 and dataTable2 have the same number, type and order of columns.

Copy a DataRow with an extra column

This should work as desired:

foreach (DataRow dr in ret.Rows)
{
DataRow row = dt.Rows.Add();
for (int i = 0; i < dr.ItemArray.Length; i++)
row.SetField(i, dr.ItemArray[i]);
row.SetField(dt.Columns.Count - 1, "1");
}

Another approach is to assign a DefaultValue to the last column since you're using always the same constant value:

dt.Columns[dt.Columns.Count - 1].DefaultValue = "1";

Now you don't need to provide this value. You can use DataTable.Merge:

dt.Merge(ret);

More Efficient way to Copy DataRows into another DataTable

As far as I know, there is no other way of copying multiple rows from one Datatable to another than iterating through all the rows. In fact, on MSDN there is an article telling you how to copy rows between Datatables and uses an iteration loop.

https://support.microsoft.com/en-gb/kb/305346

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

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()


Related Topics



Leave a reply



Submit