Search code examples
vb.netlistboxintegerstreamreader

Reading integers from a text file only and separating


I have created a program that successfully reads integers only from a text file that contains string as well into a listbox. For example: The text file contains:

  • Tyler 7
  • Daniel 2
  • Mike 6
  • Rory 9

The listbox will then show: 7269. However I plan to sort these numbers from highest to lowest (vice versa) and in order to do this I want to try store each number on a new line in the listbox but I'm not sure how to accomplish this. The code I have used to read integers only is:

    Dim intOnly As String = IO.File.ReadAllText(File_1)

    Dim intValue As String = String.Empty

    For Each c As Char In intOnly

        If IsNumeric(c) Then

            intValue += c

        End If

    Next

    ListBox3.Items.Add(intValue)
End Sub

Solution

  • Try this:

    Private Sub test()
        Dim sr As New System.IO.StreamReader("file.txt")
        Dim LofInt As New List(Of String)
    
        While sr.Peek <> -1
            Dim line As String = sr.ReadLine
            Dim intValue As String = String.Empty
    
            For Each c As Char In line
                If IsNumeric(c) Then
                    intValue += c
                End If
            Next
    
            LofInt.Add(intValue)
        End While
    
        sr.Close()
    
        LofInt.Sort()
        For Each i In LofInt
            ListBox1.Items.Add(i)
        Next
    
    End Sub
    

    So basicly what we do: We read you file line by line and store the numeric values. after each line we add what we've got to a list. After that we use a function of that list to sort the "numers" (still a string, so we should say text) and add them to your listbox