Forms in C# .NET
I have 2 textbox's & one button on Form1 and one textbox1 on Form2 when I Click on button of Form1 I want to save with file name which contains in textbox1 of Form2 with informat开发者_开发知识库ion of textboxes in Form1
As per my understanding you need to access data of one form in another form. There may be other ways to do this, one of them is you can make an event and make an event handler where you can put the code to write the file. This may help.
You can use the .Text property of the Text Box to get the text which is in typed in the TextBox.
For example
TextBox1.Text
There are many methods to write to a text file so i'll give only 1 method.
// 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();
Taken from: MSDN
So if you know about these two methods, I think the rest is your logic.
Is there anything else that you want to achieve?
Put Ranhiru Cooray's code (which writes text into a file) into an event handler attached to the OnClick
event of the button (which is invoked when the button is clicked).
To extend Ranhiru's answer, its best to put the StreamWriter creation in a using statement due to it being an unmanaged resource:
// 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());
}
The using statement ensures that Dispose is called on the StreamWriter regardless of whether it succeeds or fails. It is possible to add the call to Dispose in the "Finally" block but this method is shorter and cleaner.
More information and a complete example can be found from MSDN
精彩评论