Hey all need a lil help sorting a loop for this table out, cant seem to apply a working example to the model, anyway here it goes.
I have 2 datatables, each with different data and different values, the only value in common is the date. The first table has everything I want in it except a single column of values (from the other table) So I need to merge this column onto the first table, not all the other data with it.
So ideally I’d like something that looks like this:
DataTable tbl1; //Assume both are populated
DataTable tbl2;
tbl1.Columns.Add("newcolumnofdata") //Add a new column to the first table
foreach (DataRow dr in tbl.Rows["newcolumnofdata"]) //Go through each row of this new column
{
tbl1.Rows.Add(tbl2.Rows["sourceofdata"]); //Add data into each row from tbl2's column.
tbl1.Columns["date"] = tbl2.Columns["date"]; //The date field being the same in both sources
}
If anyone can help out wud appreciate it, like I say I just need the one column, I don’t need to have the whole of the other datatable. Cheers.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
if the second table already has all rows, but just one column is missing
it should be enough to do something like this
DataTable tbl1;
DataTable tbl2;
tbl1.Columns.Add("newCol");
for(int i=0; i<tbl.Rows.Count;i++)
{
tbl1.Rows[i]["newcol"] = tbl2.Rows[i]["newCol"];
tbl1.Rows[i]["date"] = tbl2.Rows[i]["date"];
}
Method 2
Assuming that the row counts match and are properly ordered, you should just be able to do this…
for(int i = 0; i < tbl1.Rows.Count; i++)
{
tbl1.Rows[i]["newcolumnofdata"]= tbl2.Rows[i]["newcolumnofdata"];
}
I’m not sure where the date assignment comes from, though.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0