2012-07-04 40 views
1

我只是想將List作爲DataTable整行添加。這是我嘗試過的代碼。使用列表一次性將整行添加到DataTable中

private static DataTable _table = new DataTable(); 

List<string> tempList = new List<string>(); 

// tempList = {"A1","A2","A3","A4","A5","A6"} 

_table.Rows.Add(tempList); 

預期輸出:

 col1|col2 |col3 |col4 |col5| col6 
     ----+-----+-----+------+----+-- 
row1 A1 | A2 | A3 | A4 | A5 | A6 

然而,這不是爲我工作。它會將數據收集插入到第一列。

實際輸出:

 col1  |col2 |col3 |col4 |col5| col6 
     ----------+-----+-----+------+----+-- 
row1 A1,A2,A3.|  |  |  | | 

請幫我用列表添加整個行。謝謝

+0

是否定義在數據表某些列? – dash

+0

是的。但是,tempList.ToArray()是解決方案。 :0 – devan

+0

理想情況下,你需要做兩個,否則你可以遇到問題:-) – dash

回答

3

Rows.Add()接受parms [],你可以通過將你的list轉換成一個數組來實現它。

_table.Rows.Add(tempList.ToArray()); 
+0

不能接受2個答案。投了票。 – devan

1
DataTable dt = new DataTable(); 
     dt.Columns.Add(); 
     dt.Columns.Add(); 
     dt.Columns.Add(); 
     List<string> tempList = new List<string>() { "a", "b", "c" }; 
     dt.Rows.Add(tempList.ToArray<string>()); 
相關問題