Samuel Bainbridge
Samuel Bainbridge

Reputation: 1

VB.net: What is wrong with code for reading from a file and adding the items to a list

I am coding a game that makes use of a leaderboard in vb.net, and in order to do that, I made a text file and put it in system resources, in order to be read by a streamreader. The code does not yet order the data, so I just added some test data manually into the file.

I inputted the following code:

Imports System.IO
Public Class Leaderboard
    Public Sub readfromfile()
        Dim line As Integer = 0
        Dim text As String
        Dim namelist As New List(Of String)
        Dim scorelist As New List(Of Integer)
        Using sr As StreamReader = New StreamReader(My.Resources.scores)
            Do
                text = sr.ReadLine()
                If line Mod 2 = 0 Then
                    namelist.Add(text)
                Else
                    scorelist.Add(text)
                End If
                line += 1
            Loop While text <> Nothing

        End Using
        For i = 0 To namelist.Count
            lblnames.Text = lblnames.Text & vbNewLine & namelist(i)
            lblscores.Text = lblscores.Text & vbNewLine & scorelist(i)
        Next
    End Sub
End Class

I expected this to loop through the text file and add the contents of even numbered lines to 'namelist' and odd numbered lines to 'scorelist', then output those lists using the for loop at the end, but when I run the code, nothing show up in either of the labels.

Upvotes: 0

Views: 43

Answers (1)

dbasnett
dbasnett

Reputation: 11773

An alternative approach,

Public Sub readfromfile()
    Dim line As Integer = 0
    Dim text As String
    Dim namelist As New List(Of String)
    Dim scorelist As New List(Of Integer)
    Dim lines() As String = IO.File.ReadAllLines(My.Resources.scores)
    For Each ln As String In lines
        If line Mod 2 = 0 Then
            namelist.Add(ln)
            lblnames.Text = lblnames.Text & ln & vbNewLine
        Else
            scorelist.Add(ln)
            lblscores.Text = lblscores.Text & ln & vbNewLine
        End If
        line += 1
    Next
    lines = Nothing
End Sub

Upvotes: 0

Related Questions