2017-08-28 78 views
1

我使用follwoing代碼將數據格式視圖中的條目打印到文本文件中,方法是將它們轉換爲字符串!數據網格視圖有3列(第3列有幾個字符串),我想在文本文件中將每個數據網格視圖行打印爲一行!C#字符串不打印在同一行StreamWriter問題

private void button1_Click_1(object sender, EventArgs e) // converting data grid value to single string 
     { 

      String file = " " ; 
      for (int i = 0; i < dataGridView2.Rows.Count; i++) 
      { 
       for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++) 
       { 
        if (dataGridView2.Rows[i].Cells[j].Value != null) 
        { 
         if (j == 0) 
         { 
          file = Environment.NewLine + file + dataGridView2.Rows[i].Cells[j].Value.ToString(); 
         } 
         else 
         { 
          file = file + dataGridView2.Rows[i].Cells[j].Value.ToString(); 
         } 
        } 


       } 



       using (StreamWriter sw = new StreamWriter(@"C:\Users\Desktop\VS\Tfiles\file.txt")) 
       { 


        { 
         sw.Write(file); 
        } 
       } 

      } 
     } 

雖然一個文本文件創建第一2列和在第三列中的第一串被印刷在同一行上,但第3列的其它字符串被打印在一個新行!我怎麼能讓他們到同一條線上。 (aaa)(bbb)(ccc dddd eee)並且它必須出現在文本文件中作爲aaa bbb ccc dddd eee但是從我的代碼它看起來像aaa bbb ccc on同一行,dddd放在一個新行上,eee放在另一行新行!我如何糾正這個問題?

+0

看來你不想要你的文本文件中的新行是否正確?那麼只需在第一個循環中省略換行符呢? –

+0

讓我確保我在這裏正確理解你:你希望你的gridview中的所有項目按照列的順序出現在文本文件中。因此,第1列中的所有項目都被添加,然後在同一行中添加第2列中的所有項目,等等。全部沒有新行? –

+0

耶列1和列2都可以!第3列的第一個字符串也打印在同一行上!但在此之後,第3列的其他字符串會打印在換行符上! –

回答

0

而不是依靠j==0的,可以追加新行的內外面循環。同樣要放入很多字符串值,您應該使用StringBuilder。試試這個:

private void button1_Click_1(object sender, EventArgs e) // converting data grid value to single string 
{ 

    StringBuilder file = new StringBuilder(); 
    for (int i = 0; i < dataGridView2.Rows.Count; i++) 
    { 
     for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++) 
     { 
      var val = dataGridView2.Rows[i].Cells[j].Value; 
      if (val == null) 
       continue;//IF NULL GO TO NEXT CELL, MAYBE YOU WANT TO PUT EMPTY SPACE 
      var s=val.ToString(); 
      file.Append(s.Replace(Environment.NewLine," ")); 
     } 
     file.AppendLine();//NEXT ROW WILL COME INTO NEXT LINE 
    } 

    using (StreamWriter sw = new 
        StreamWriter(@"C:\Users\Desktop\VS\Tfiles\file.txt")) 
    { 
     sw.Write(file.ToString()); 
    } 
} 

編輯: -似乎第三列包含新行字符串,這樣我們就可以把到文件之前,從字符串中刪除新行:

var s = val.ToString(); 
file.Append(s.Replace(Environment.NewLine, " ")); 
+0

非常感謝! –

0

試試這個:

 for (int i = 0; i < dataGridView2.Rows.Count; i++) 
     { 
      for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++) 
      { 
       if (dataGridView2.Rows[i].Cells[j].Value != null) 
       { 
        file = file + dataGridView2.Rows[i].Cells[j].Value.ToString(); 
       } 
      } 
+0

是的,但文件+ =東西是相同的文件=文件+東西正確嗎? –

+0

編輯,以調整新的信息@KushanPeiris –