2010-10-03 55 views
1

我在Form 2文本框的&一個按鈕,並在Form2一個TextBox1中,當我點擊Form1上的按鈕,我想保存與包含在文本框的信息的Form2 TextBox1的Form1中形式在C#.NET

文件名

回答

4

您可以使用文本框的.Text屬性來獲取文本框中鍵入的文本。

例如

TextBox1.Text

有許多方法寫入一個文本文件,所以我就給只有1方法。

// Compose a string that consists of three lines. 
string myText= TextBox1.Text; 

// Write the string to a file. 
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt"); 
file.WriteLine(myText); 

file.Close(); 

來自:MSDN

所以,如果你知道這兩種方法,我覺得剩下的就是你的邏輯。

還有什麼你想實現的?

+0

'c:\\ test.txt'不是一個很好的示例目錄,可以在其中創建該文件。 – ChrisW 2010-10-03 14:54:16

+1

Comp表決,編寫代碼將挑選一個安全的目錄將戲劇性地模糊片段。 – 2010-10-03 15:38:45

+0

@ChrisW:該目錄是他/她的選擇。這只是一個例子:) – 2010-10-03 15:42:05

2

將Ranhiru Cooray的代碼(將文本寫入文件)插入到附加到the OnClick event of the button(單擊按鈕時調用該事件處理程序)的事件處理程序中。

2

爲了延長Ranhiru的答案,最好把StreamWriter創作using語句,由於它是一個非託管資源:

// Attempt to write to the file 
try 
{ 
    // Compose a string that consists of three lines. 
    string myText= TextBox1.Text; 

    // Write the string to a file. 
    using(System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt")); 
    { 
     file.WriteLine(lines); 
    } 
} 
catch(IOException exception) //Catch and display exception 
{ 
    MessageBox.Show(exception.Message()); 
} 

using statement確保調用Dispose在StreamWriter不管是否成功或失敗。可以在「最後」塊中添加對Dispose的調用,但此方法更短且更清晰。

更多信息和完整的例子可以從MSDN

6

按我的理解,你需要訪問的另一種形式一種形式的數據中找到。可能有其他方法可以做到這一點,其中之一是您可以創建事件並創建一個事件處理程序,您可以在其中放置代碼以寫入文件。這可能有幫助。