private void sessionText()
{
try
{
System.IO.TextReader r = new System.IO.StreamReader("saved.txt");
this.textBox1.Text = r.ReadLine();
r.Close();
}
catch (Exception x)
{
MessageBox.Show("Exception " +x);
}
}
It reads the line into textBox1 but now I’m expanding my application. I added 5 more textBoxes and now I’m trying to load the data in each one saved line by line. How can I load each line into the next textbox?
Line 0 -> textBox1
Line 1 -> textBox2
Line 2 -> textBox3
If you don’t want this to be a generic method then simply call the ReadLine method again and assign the result to textBox2.Text and so on:
Note that the TextReader should be Disposed. That is you need to call it’s Close() or Dispose() method because it is an IDisposable. In fact any object that implements the IDisposable interface must to disposed.
you normally do this using the “using” construct. But in your case, because you’ve also got a try-catch, you could do it like this:
There is an assumption you’re making with this code though. By this code I mean all of the code I’ve listed as well as the code you’ve listed and that is, there are guaranteed to be 3 lines of text in the file you’re reading. Not this might always be the case (in your situation, but you may want to look at a more defensive approach to this kind of thing.
Also, you’ve already had to modify the code from 2 line and 1 textbox to 3 lines and 3 textboxes. Maybe it’s time to look at implementing this in such as way that the next time (when your requirements go from say 3 to 10) you don’t have to modify your code but rather let it know (some how) about the additional textboxes and it should do the right thing? Or maybe there is something in your application that knows the number of “lines” (whatever they signify) and you could use this information?
Just a thought.