简体   繁体   English

将DataTable列的值复制到另一个DataTable行C#

[英]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 源表的行不能大于7行

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. 此处dt1dt2分别是源表和目标表。

Assume that dt1 is having same number of rows as the number of columns in dt2 . 假设dt1的行数与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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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