tags:

views:

177

answers:

2

Hi, I have a DataTable populated with values from a database. I have another datatable that I am creating which has the same column names from the first, pluse some extra data that I need for creating a CSV down the line. What I would like to do is take the data from the first table and use it to populate the second table, then later on I can fill in the other data.

I know I can do this in a very mechanical fashion, by looping though, creating new rows and then populating cell for cell from the first table.

I'm hoping someone knows something a little slicker.

Jim

+3  A: 

I think this is what you are looking for DataTable.Merge

Darnell
works like a charm
jim
+2  A: 

You can use the Merge method on the datatable. The only thing you need to be aware of is that both DataTables need to have a primary key. The one that comes from the DB probably already does, but then one you're populating in memory most likely does not.

You can easily set the primary key like this:

table.PrimaryKey = new DataColumn[] { table.Columns[0]}; //or whatever column you want.
BFree
I did not find this to be true. All had had to do was wire up the column names to be the same.
jim
Yes, but if you have two rows that are the same in both tables, with only slightly different values, instead of an update, it'll do an insert, and you'll end up with two rows instead of one updated row.
BFree
ok...good point...as I was doing a straight insert this problem didn't arise.
jim