views:

1341

answers:

2

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.

+2  A: 

hi if the second table already has all rows, but just one column is missing it should be enough to 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"];
}
nWorx
Thanks for that, works a treat.
markdigi
A: 

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.

Adam Robinson