2017-02-26 171 views
0

我有两个数据表两个数据表都由七列组成。我想将第一个数据表的列值复制到第二个数据表行中。如预期将DataTable列的值复制到另一个DataTable行C#

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); 
     } 
    } 

不知道如何每个值转移到相应的列源表中的行不能大于7行

为例

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

我发现这个功能,但这个不是作品在目的地表中?

+1

如果第一个表格包含多于7行,该怎么办?或者那根本就不是条件?基本上你想要将行转换为列? –

+0

对不起,我忘了提到源表的行不能超过7行 – Kamran

+0

看起来你实际上只需要__one__循环吗? - ) – TaW

回答

2

以下是样本代码。这里dt1dt2分别是源表和目的表。

假设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]); 
} 
+0

谢谢你这么多。我在你的代码片段中做了一些改变,它按预期工作 – Kamran

相关问题