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.
How to copy specific rows from one datatable to another based on a specific datarow
You can follow this logic to search the UsersTable and copy whole row (except last column) to the destination tables based on a column value. This method has a better performance as it traverses the UsersTable once.
foreach(DataRow dRow in Usersdt.Rows)
{
DataTable destinationTable = null;
if (dRow.Field<string>("UserType") == "student")
destinationTable = Studentsdt;
else if (dRow.Field<string>("UserType") == "Faculty")
destinationTable = Facultydt;
else
continue; // skip the current row
// copy the row skipping the last column as required
object[] rowData = new object[dRow.ItemArray.Length - 1];
Array.ConstrainedCopy(dRow.ItemArray, 0, rowData, 0, rowData.Length);
destinationTable.Rows.Add(rowData);
}
Copy a range of data rows to another datatable - C#
If it's about readability, then a good idea would be to throw this into an extension method.
Without changing your logic:
public static class Utils
{
public static void CopyRows(this DataTable from, DataTable to, int min, int max)
{
for (int i = min; i < max && i < from.Rows.Count; i++)
to.ImportRow(from.Rows[i]);
}
}
Then you can always reuse it without all the fancy syntax and know that it does exactly what you need if there is a concern of performance:
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.CopyRows(dt2, 30, 50);
Copying Rows from One DataTable to another Displays Nothing
Fill the columns correctly:
For Each dc As DataColumn In lineTable.Columns
lftable.Columns.Add(new DataColumn(dc.ColumnName, dc.DataType));
Next
You can use the overload of the Row.Add
function which allows you provide the ItemArray
directly:
For Each dr As DataRow In ds.Tables(0).Rows
lftable.Rows.Add(dr.ItemArray)
'nRow.ItemArray = dr.ItemArray() <-- remove
Next
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
Copying one datatable to another datatable c#
Datatable dt may have rows which has null values for column date
Use nullable DateTime while comparing date
dt3 = dt.AsEnumerable()
.Where(rows => rows.Field<DateTime?>("date") == cellData )
.CopyToDataTable();
Copy specific rows from One DataTable to another DataTable using LINQ
Using Select
on PROD ID
means you are trying to store collection of string in a column which supports storing a string value. This will by default calls ToString method on a collection and results in System.Linq... string value in a column.
You want to use appropriate function to get all values in the column:
var newDt = dt.AsEnumerable()
.GroupBy(r => r.Field<string>("BATCH NUM"))
.Select(g =>
{
var row = dt.NewRow();
row["BATCH NUM"] = g.Key;
row["QTY"] = g.Sum(r => Convert.ToInt32(r.Field<string>("QTY")) + Convert.ToInt32(r.Field<string>("BONUS")));
row["PROD ID"] = String.Join(",", g.Select(x => x.Field<string>("PROD ID")).Distinct());
return row;
}).CopyToDataTable();
Copy row from datatable to another where there are common column headers
I think this is your homework, but here you have some simple and not very smart solution:
private DataTable DTCopySample()
{
int cnt = 0;
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID");
dt1.Columns.Add("aaa");
dt1.Columns.Add("bbb");
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID");
dt2.Columns.Add("ccc");
dt2.Columns.Add("bbb");
dt2.Columns.Add("aaa");
dt1.Rows.Add();
dt1.Rows[0]["ID"] = "23";
dt1.Rows[0]["aaa"] = "val1";
dt1.Rows[0]["bbb"] = "val2";
dt1.Rows.Add();
dt1.Rows[1]["ID"] = "99";
dt1.Rows[1]["aaa"] = "val99";
dt1.Rows[1]["bbb"] = "val98";
string colName = string.Empty;
foreach (DataRow row in dt1.Rows)
{
dt2.Rows.Add();
foreach (DataColumn col in dt1.Columns)
{
dt2.Rows[cnt][col.ColumnName] = row[col.ColumnName].ToString();
}
cnt++;
}
return dt2;
}
There are more smart and better solutions, but this is fast-written (2 mins) and works.
Remeber, that you have not specified columns datatypes or anything else, so I assumed there are strings everywhere for creating simple sample.
Copy data from DataColumns from one DataTable to another
With the given example data, you can simple use the DataTable.Copy method to copy the entire datatable with structure and dataRows:
var copyDataTable = dataTable.Copy();
After that you can set the DataColumn.DefaultValue property for the third column. When adding new rows, this value is automatic being set:
copyDataTable.Columns["Status"].DefaultValue = "OK";
Related Topics
Attach Debugger in C# to Another Process
Win32_Processor::Is Processorid Unique for All Computers
Get SQL Query from Linq to SQL
C#: Prepending to Beginning of a File
What's Better: Dataset or Datareader
Optimal Way to Read an Excel File (.Xls/.Xlsx)
Convert String to Hex-String in C#
Send Smtp Email Using System.Net.Mail via Exchange Online (Office 365)
Creating Delegates Manually VS Using Action/Func Delegates
ASP.NET MVC 4 Multiple Post via Different Forms
How to Execute a Command in a Remote Computer
How to Call C# Dll Function from Vbscript
File Getting Copied to Syswow64 Instead of System32
What Is the JSON.Net Equivalent of Xml's Xpath, Selectnodes, Selectsinglenode