2010-02-12 84 views
0

我正在寻找从DataTable对象获取列及其所有行数据,然后在另一个数据表中创建一个新列,并将其添加到新列及其行中。我一直遇到的问题是行数据会出来,列名也会出现,但所有行都附加到同一列,我敢肯定,我错过了一些明显的事情,事实上我知道我是!任何帮助都很受欢迎。.Net DataTable列导出

void GetColumns() 
    { 
     // add the columns to the new datatable 
     foreach (int i in mapValues) 
     { 
      SplitData.Columns.Add(i.ToString()); 
     } 
     // map values contains the index numbers of my target columns 
     foreach (int x in mapValues) 
     { 

      foreach (DataRow row in OrigData.Rows) 
      { 
       SplitData.Rows.Add(row[mapValues[LocalIndex]]); 
      } 

      LocalIndex++; 
     } 
    } 
+0

请发布(大纲)您的代码。 – 2010-02-12 10:25:30

+0

这是问题出在哪里,我知道我需要以某种方式遍历列和列一起遍历,尽管我还没有看到明确的方法来执行此操作... – Yoda 2010-02-12 10:45:37

回答

1

您正在使用的DataRow.Add超载是PARAMS一个,所以你只是把你的原稿列数据在新的DataTable的第一列。

你可能想是这样的:

DataRow newRow = SplitData.NewRow(); // gets a new blank row with the right schema 
newRow[x.ToString()] = row[mapValues[LocalIndex]; // sets the column (that you created before) to the orig data 
SplitData.Rows.Add(newRow); 

为你的第二个for循环的核心。你也可以在一个循环中完成它。

+0

干杯伙伴我知道这是简单的事情 – Yoda 2010-02-12 11:40:10

0

虽然接受的答案是完全正确的,但我从中学到了一些东西,结果证明DataTable.ImportRow方法正是我所需要的,所以只是为了将来的参考。