2010-10-03 40 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

按我的理解,你需要访问的另一种形式一种形式的数据中找到。可能有其他方法可以做到这一点,其中之一是您可以创建事件并创建一个事件处理程序,您可以在其中放置代码以写入文件。这可能有帮助。