2016-10-07 49 views
0

我的DataTable行像40行的DataGridView 顯示我很困惑,爲什麼我的方法只保存One RowTextFileC#寫上我的<code>DataTable</code>在TXT文件

private void SaveBtn_Click(object sender, EventArgs e) 
    { 
     String outputFile; 
     List<String> ListData = new List<String>(); 
     using (SaveFileDialog sfd = new SaveFileDialog()) 
     { 
      sfd.Filter = "Txt File|*.Txt"; 
      if (sfd.ShowDialog() != DialogResult.OK) 
       return; 
      outputFile = sfd.FileName; 
     } 

     DataTable tb = pw.SavedInfo(User_info.UserID); 

     for (int i = 0; i < tb.Rows.Count; i++) 
     { 
      ListData.Add("Name==> " + tb.Rows[i][1].ToString() + " LastName ==> " + tb.Rows[i][2].ToString() + " Email ==> " + tb.Rows[i][3].ToString()); 

     } 

     foreach (String s in ListData) 
     { 
      using (TextWriter Tw = new StreamWriter(outputFile)) 
      { 
       Tw.WriteLine(s); 
      }    
     } 
    } 

難道我錯過了什麼?造成這是一個非常漫長的一天,以保持被聚焦

回答

2

使用相同StreamWriter

using (TextWriter Tw = new StreamWriter(outputFile)) 
{ 
    foreach (String s in ListData) 
    { 
     Tw.WriteLine(s);    
    } 
} 

或使用constructor that takes a boo升爲「追加」:

foreach (String s in ListData) 
{ 
    using (TextWriter Tw = new StreamWriter(outputFile, true)) 
    { 
     Tw.WriteLine(s); 
    }    
} 
2
File.WriteAllLines(outputFile, lisData); 

使用此寫入文件。 File.WriteAllLines Documentation

+0

我v先使用Foreach然後TextWriter我不得不在循環之前使用textwriter,但是謝謝先生! –

+1

'File.WriteAllLines(...)'這個重載需要'IEnumerable '所以你不需要'foreach'或'StreamWriter' https://msdn.microsoft.com/en-us/library /dd383693(v=vs.110).aspx –