Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27192

conversion from string to type 'integer' is invalid error from text file

$
0
0
Hello again. I can't find my error in this code. Anyway, the assignment problem is to create a application that generates hundred numbers from 1 to 1000 and save the numbers to a file. The chapter only shows how to save to text file. I've decided to add a function to be able to load those saved numbers into the application. When I go to open the file, I get the error in the subject heading.

Code:

Dim inputFile As StreamReader
        Dim strNumber(99) As String

        Try
            ofdOpenFile.Title = "Open File"
            ofdOpenFile.Filter = "Text Files (*.txt)|*.txt"
            If ofdOpenFile.ShowDialog() = Windows.Forms.DialogResult.OK Then
                strFileName = ofdOpenFile.FileName
                inputFile = File.OpenText(strFileName)
                For intCounter = 0 To 99
                    strNumber(intCounter) = inputFile.ReadLine(strFileName)
[will add code to convert to integer]
                    lstOutput.Items.Add(intRandomNumbers(intCounter))
                Next
                inputFile.Close()
            End If
        Catch ex As Exception
            MessageBox.Show("Error retrieving data" & ControlChars.CrLf & ex.Message, "Open File Error")
        End Try

I also tried with no luck, per Visual Studio suggestion
Code:

intRandomNumbers(intCounter) = Val(inputFile.ReadLine(strFileName))
intRandomNumbers array is declared as Class variable

Just in case, this is how I generated the numbers
Code:

For intCounter = 0 To 99
            intRandomNumbers(intCounter) = (rand.Next(1000) + 1)    'generate a number
            lstOutput.Items.Add(intRandomNumbers(intCounter))  'add to ListBox items collection
        Next

I assume the data being pulled from the saved file, even though a text file, would be just string data, and thus need to converted to an integer. But I'm just not sure why it's all trying to convert to an integer when trying to add to a string array.

Thanks for any guidance/help in advance.

Viewing all articles
Browse latest Browse all 27192

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>