2011-05-31 35 views
12

我有一個場景,我得到一個數據表,65列和100行。我需要再創建一個包含所有100行的數據表,即與原始數據表相同,但應該只有原始表中65個列中的5個列。有沒有什麼辦法可以實現這個沒有循環?只有幾列的數據複製到另一個數據表

+0

西隧r爲列做ü要保留?前五個或最後五個或選定的五列?明確提及它。 – thevan 2011-05-31 06:34:30

+0

@ thevan我有一些選定的列 – satyajit 2011-05-31 06:36:18

+0

嗨Satyajit。我編輯了我的答案。它會給你問題的最終解決方案。 – thevan 2011-05-31 07:17:50

回答

26

嘗試DataView.ToTable方法。

使用方法如下:

DataTable newTable = oldTable.DefaultView.ToTable(false, "ColumnName1", "ColumnName2", "ColumnName3", "ColumnName4", "ColumnName5"); 
+0

它會複製行還 – satyajit 2011-05-31 06:38:50

+0

哦,抱歉,這將無法正常工作。我更新了我的答案。 – Reniuz 2011-05-31 06:45:37

+0

太棒了!你節省了我的時間:D – Tony 2016-08-17 15:50:48

3
DataTable oldTable = new DataTable(); 
DataTable newTable = oldTable.Copy(); 
for (int i = 5; i < 65; i++) 
{ 
    newTable.Columns.RemoveAt(i); 
} 
2

嘗試這樣,

DataTable newTable = oldTable.Copy(); 
newTable.Columns.Remove("ColumnName"); 

您在這裏刪除不需要的列。

這裏是你的問題的最佳解決方案:

DataTable dt = new DataTable(); 
string [] column = {"Column1", "Column2"}; 
dt = DTItem.DefaultView.ToTable("dd", false, column);  
//DTItem is the Existing Table and "dd" is the temporary tablename, u give whatever u want 
1
private void button3_Click(object sender, EventArgs e) 
    { 
     DataTable destiny = new DataTable(); 
     destiny.Columns.Add("c1"); 
     destiny.Columns.Add("c2"); 
     destiny.Columns.Add("c3"); 
     destiny.Columns.Add("c4"); 

     CopyColumns(dtST_Split, destiny, "c1", "c2","c3","c4"); 

    } 

    private void CopyColumns(DataTable source, DataTable dest, params string[] columns) 
    { 
     foreach (DataRow sourcerow in source.Rows) 
     { 
      DataRow destRow = dest.NewRow(); 
      foreach (string colname in columns) 
      { 
       destRow[colname] = sourcerow[colname]; 
      } 
      dest.Rows.Add(destRow); 
     } 
    } 
+0

你可以添加一些上下文到你的答案? – Dev2rights 2013-05-26 18:19:50

相關問題