470,621 Members | 1,516 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,621 developers. It's quick & easy.

How to move text from a text file to a text box line by line

Alrighty, so I have a text file with a lot of different things in, but what I want is for when a button is pressed, only 1 row of text is shown. For example the text file says
Potato - Potato
I want the text box to say only Potato - Potato, nothing else in the file until the button is clicked again, which then will move onto showing the next line of text. If this is possible let me know, best way of informing me how it is done is by video as I find it the easiest, but text is fine, pictures will be very helpful also. Thanks.
Dec 3 '14 #1
3 1345
9,735 Expert Mod 8TB
Well, you need to read the file into memory and then use the StreamReader.Readline Method to retrieve the next line and display it.

Check out the link for an example of how to use the ReadLine method.

Dec 3 '14 #2
Read the file into memory? Could you expand? I'm quite new to VB, sorry... Thanks for the help though :)
Dec 4 '14 #3
9,735 Expert Mod 8TB
The example in the documentation demonstrates it pretty well.

This example creates a new file that it then reads in (if the file exists before creation it deletes the file and creates a new one).
Expand|Select|Wrap|Line Numbers
  1. Imports System
  2. Imports System.IO
  3. Imports System.Text
  5. Public Class Test
  7.     Public Shared Sub Main()
  8.         Dim path As String = "c:\temp\MyTest.txt" 
  10.         Try 
  11.             If File.Exists(path) Then
  12.                 File.Delete(path)
  13.             End If 
  15.             Dim sw As StreamWriter = New StreamWriter(path)
  16.             sw.WriteLine("This")
  17.             sw.WriteLine("is some text")
  18.             sw.WriteLine("to test")
  19.             sw.WriteLine("Reading")
  20.             sw.Close()
  22.             Dim sr As StreamReader = New StreamReader(path)
  24.             Do While sr.Peek() >= 0
  25.                 Console.WriteLine(sr.ReadLine())
  26.             Loop
  27.             sr.Close()
  28.         Catch e As Exception
  29.             Console.WriteLine("The process failed: {0}", e.ToString())
  30.         End Try 
  31.     End Sub 
  32. End Class
The Peek method is used to check if the stream that contains the file has another line available for reading. If the Peek method returns a line that has a lenght greater than 0 it reads it in and displays it on the screen.

The try/catch block is there in case something goes wrong creating the file or reading the file.

Dec 4 '14 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

By using this site, you agree to our Privacy Policy and Terms of Use.