簡體   English   中英

將DataTable列的值復制到另一個DataTable行C#

[英]Copy DataTable Column's values into another DataTable row C#

我有兩個數據表兩個數據表都由七個列組成。 我想將第一個數據表的列值復制到第二個數據表行中。 源表的行不能大於7行

例如

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

我已經找到了此功能,但無法正常工作

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

任何想法如何將每個值移動到目標表中的適當列?

以下是示例代碼。 此處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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM