2016-08-03 52 views
-1

添加在數據表中的列明智的行值如何在數據表中如何從循環

代碼

DataTable dt = new DataTable(); 
      dt.Clear(); 
      DataColumn dc = new DataColumn("day1", typeof(String)); 
      dt.Columns.Add(dc); 

      dc = new DataColumn("day2", typeof(String)); 
      dt.Columns.Add(dc); 

      dc = new DataColumn("day3", typeof(String)); 
      dt.Columns.Add(dc); 

tString[0] = "Sat,mon,tue"; 
tString[1] = "Fri,,wed"; 
tString[2] = "Thu,"; 

int lengthA = tString.Length; 

for (int i = 0; i <= lengthA - 1; i++) 
      { 
       string s = tString[i]; 

        string[] words = s.Split(','); 
        foreach (string word in words) 
        { 
          dt.Rows.Add(word); 
        } 

       } 

在dt.Rows.Add(字)的問題,因爲添加行它被插入行

期望輸出

DATATABLE值應該是

day1, day2, day3 

sun,mon,tue 
Fri,Wed 
Thu 

熱來實現這一點,任何一個可以幫助我

+0

「星期五」和「星期三」之間的雙重逗號是有意的還是錯誤的? –

回答

2

只需創建一個NewRow(),然後將值添加到其Item indexer爲每列。

for (int i = 0; i <= lengthA - 1; i++) 
{ 
    string s = tString[i]; 
    string[] words = s.Split(','); 
    // here is the new row 
    var row = dt.NewRow(); 
    for(int w = 0; w < words.Length; w++) 
    { 
     // set each column 
     row[w] = words[w];  
    } 
    // don't forget to add the Row to the Rows collection 
    dt.Rows.Add(row); 
}