简体   繁体   中英

Copy DataTable Column's values into another DataTable row C#

I have two data tables Both Data table are consist on seven columns. I want to copy column values of first data table into second data table row. Source table's rows cannot be greater than 7 rows

for Example

Source          Destination 
SourceColumn    ColumnOne   ColumnTwo    ColumnThree    ColumnFour ......
   1              1           2            3                4
   2
   3
   4 
   6
   7

I have found this function but this not works as expected

   private void CopyColumns(DataTable Source, DataTable Destination, params string[] Columns )
    {
        foreach(DataRow SourceRow in dtable.Rows)
        {
            DataRow DestinationRow = dt.NewRow();
            foreach(string ColumnName in Columns)
            {
                DestinationRow[ColumnName] = SourceRow[ColumnName];
            }
            dt.Rows.Add(DestinationRow);
        }
    }

Any idea how to shift each value to appropriate column in destination table?

Following is the sample code. Here dt1 and dt2 are source and destination tables respectively.

Assume that dt1 is having same number of rows as the number of columns in dt2 .

var newRow = dt2.NewRow();  //dt2 is the destination table. Creating new row for destination table.

for (var i = 0;i < dt2.Columns.Count;i++)
{
    var row1 = dt1.Rows[i];
    newRow[i] = row1[0];
}

dt2.Rows.Add(newRow); //Adding new row to the destination table.

var xRow = dt2.Rows[0]; //Retrieving row for displaying the data to Console.

for (var j = 0; j < dt2.Columns.Count; j++)
{
    Console.WriteLine(xRow[j]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM