Reputation: 2019
I have a DataTable with this structure:
DataTable1
NAME | SURNAME
Joe | Doe
John | Smith
and another table with this structure:
DataTable2
StudentName| StudentSurname | Status
Joe | Doe | OK
John | Smith | OK
I need to copy all the rows from DataTable1 to DataTable2, following this rule:
What is the best way to achieve this?
EDIT: SO far I tried to do this:
foreach (DataColumn dc in DataTable1.Columns)
{
if (DataTable1.Contains("NAME"))
{
//how can I copy it??
}
}
I'm using C#.
Upvotes: 1
Views: 1791
Reputation: 3513
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";
Upvotes: 3
Reputation: 97
you will probably want to base your foreach statement on rows instead of columns. You can iterate through the rows checking the value of that particular data row then update the value.
I think this code will do what you are looking to do.
DataTable NewTable = OldDataTable;
NewTable.Columns.Add("Status",typeOf(String));
(Adding column to DataTable: https://msdn.microsoft.com/en-us/library/hfx3s9wd%28v=vs.110%29.aspx)
ForEach( DataRow row in NewTable)
{
//you can reference a column by it's name to assign and check values.
//It's used here to get the column number: http://stackoverflow.com/questions/11340264/get-index-of-datatable-column-with-name
if (row["Name"] == "John")
{
row["Status"] = true;
}
}
If you only want the last DataTable to have rows matching true. Use another foreach to go through the data table and remove the rows where row["Status"] != true.
Upvotes: 1