How can we copy the column data of one datatable to another,even if there is different column names

Posted by Harikrishna on Stack Overflow See other posts from Stack Overflow or by Harikrishna
Published on 2010-04-07T13:09:47Z Indexed on 2010/04/07 13:13 UTC
Read the original article Hit count: 1099

Filed under:
|
|
|
|

I have two datatables. First is

DataTable NameAdressPhones = new DataTable(); 

with Three columns Name,Adress and PhoneNo.But I want only two columns Name and Adress data so I am copy those columns (with data) to the new datatable

DataTable NameAdress = new DataTable(); 

For that I do

            foreach (DataRow sourcerow in NameAdressPhones.Rows)
            {
                DataRow destRow = NameAdress.NewRow();
                foreach (string colname in columns)
                {
                    destRow[colname] = sourcerow[colname];
                }
                NameAdress.Rows.Add(destRow);
            }

Now I clear every time the NameAdressPhones(first) datatable when there are new records in the table.And every time there will be same no of columns but column name will be different like Nm instead of Name,Add instead of Address.Now problem is second datatable have already column names Name and Address and now I want to copy the columns data of Nm and Add to the second datatabel but the column names are different to the second datatable.So even If there is different column names I want to copy Nm column data of first datatable to the column Name of second datatable and column Add data of first datatable to column Address of second datatable.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET