Hello, i'm having trouble opening a text file to process and order the data in it. When i try to read the first line of characters an error message occurs saying: 'Variable words1 is used before it has been assigned a value.' I dont understand what i am doing wrong when opening the file. Also, I am sorry if this is a rather basic question.

Public Class frmAssign6
    Dim sr As IO.StreamReader = IO.File.OpenText("words.txt")

    Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click
        Dim words1 As String 'Line 1?

        While Not (sr.EndOfStream)
            words1 = sr.ReadLine
            End While

            lstResults.Items.Add(words1)
    End Sub
End Class

There are several problems with your code. I've corrected them in the following:

Public Class frmAssign6
    Dim sr As IO.StreamReader = IO.File.OpenText("words.txt")
    Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click
        Dim words1 As String = "" 'Always initialize it, just to be safe

        While Not (sr.EndOfStream)
            words1 = sr.ReadLine
            lstResults.Items.Add(words1) 'This needs to be inside the loop, or you just add the last line of the file
        End While

        sr.Close() 'Always close a file when you are done reading it
    End Sub
End Class

1. You should always give things an initial value, just to be safe (Especially if the text document may be empty. Check your words.txt and make sure there is stuff in it)

2. Your lstResults.Items.Add(words1) line should be inside the while loop. Otherwise, it loops through the file and adds only the last line.

3. Its always a good idea to close a file after you're done with it.

thanks for the tips xcelled!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.