2016-06-28 26 views
-1

這裏是問題:我有兩個班。表單1創建一個.txt文件並在其中設置兩個值(字符串)。現在,我想通過按下按鈕(bDirekt)來獲得這兩個字符串,並將每個字符串設置爲Form 2中的Textbox。如何從文本文件中獲取值並將其設置在文本框中?

Form 1(應該是正確的,據我所知,但請告訴我,錯了):

public void Txfw() 
    { 
     string txBetrag = gBetrag.Text; 
     string txMonate = gMonate.Text; 

     string[] vars = new string[] { txBetrag, txMonate }; 
     using (StreamWriter sw = new StreamWriter(@"C:\Users\p2\Desktop\variablen.txt")) 
     { 

      foreach (string s in vars) 
      { 
       sw.WriteLine(s); 
      } 
     } 
    } 

表2(有不知道如何繼續下去):

private void bDirekt_Click(object sender, RoutedEventArgs e) 
    { 
     using (StreamReader sr = new StreamReader("variables.txt")) ; 

     string line = ""; 
     while ((line = sr.ReadLine()) != null) 
     { 
      monate2.Text = 
     } 

    } 

我真的很感謝你的幫助。

回答

0

試試這個

StringBuilder sb = new StringBuilder(); 
    using (StreamReader sr = new StreamReader(@"C:\Users\p2\Desktop\variablen.txt")) 
    { 
        string line; 

        // Read and display lines from the file until 
        // the end of the file is reached. 
        while ((line = sr.ReadLine()) != null) 
        { 
         sb.Append((line); 
        } 
    } 
    monate2.Text = sb.Tostring(); 

UPDATE:要單獨一行與文本的其餘部分,你可以試試這個。總是有更好的方法來實現這一點。

StringBuilder sb = new StringBuilder(); 
    string headerLine = string.Empty; 
    int currentLine = 0; 
     using (StreamReader sr = new StreamReader(@"C:\Users\p2\Desktop\variablen.txt")) 
     { 
         string line; 

         // Read and display lines from the file until 
         // the end of the file is reached. 
         while ((line = sr.ReadLine()) != null) 
         { 
          currentLine++; //increment to keep track of current line number. 
          if(currentLine == 1) 
          { 
          headerLine = line; 
          continue; //skips rest of the processing and goes to next line in while loop 
          } 
          sb.Append((line); 

         } 
     } 
     header.Text = headerLine; 
     monate2.Text = sb.ToString(); 
+0

工作完美,幾乎是我想要的東西:)。但是,我該如何改變它,以便在另一個文本框中複製.txt文件的第一行?但它在一個方面複製了兩條線。 –

+0

請參閱我發佈的更新 – Vinod

相關問題