Error switch CVS text file item when selecting lis

2019-03-06 02:19发布

问题:

I'm trying to switch "M" to "Mr." and "F" to "Ms." when the last name is selected in the listbox. When I clicked on the first name it worked, but when I clicked on anyother name, I got this error message:

--Additional information: Index was outside the bounds of the array.--

The information in the text file is like this:

       Ball,Krystal,F,1981
       Banks,Robin,F,1988
       Burgher,Hamilton,M,1980
       Early,Brighton,M,1989
       Hedd,MT,M,1960
       Hogg,Ima,F,1953
       Knapp,Anita,F,1970
       Overnout,Roger,M,1968
       Psito,Arnie,M,1962
       Teak,Anne,F,1939

And my code is as follows:

    Private Sub btnEnter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click
    Dim names As IO.StreamReader = IO.File.OpenText("Info.txt")
    Dim lName As String = lstNames.Text
    Dim line As String
    Dim gender As String
    Dim foundFlag As Boolean = False
    Do Until foundFlag Or names.EndOfStream
        line = names.ReadLine
        If line.Split(","c)(2) = "M" Then
            gender = "Mr. "
        ElseIf line.Split(","c)(2) = "F" Then
            gender = "Ms. "
        End If
        If line.Split(","c)(0) = lName Then
            txtOutput.Text = gender & line.Split(","c)(1) & " " & line.Split(","c)(0) & " is " & 2012 - line.Split(","c)(3)
            foundFlag = True
        End If
    Loop

End Sub

Can someone please let me know what's wrong. Thanks in advance.

回答1:

I re-created your application exactly as you have it here and it worked jsut fine.

That leads me to believe one of 2 things is happening:

  1. You have bad characters in your Info.txt file
  2. You haven't populated your lstNames combobox with the identical names to what you have in Info.txt.

PS - You might also want to look into your loop to make it more efficient:

    Dim line() As String
    Dim gender As String
    Dim foundFlag As Boolean = False
    Do Until foundFlag Or names.EndOfStream
        line = names.ReadLine.Split(","c)

        If line(0) = lName Then
            If line(2) = "M" Then
                gender = "Mr. "
            ElseIf line(2) = "F" Then
                gender = "Ms. "
            End If
            txtOutput.Text = gender & line(1) & " " & line(0) & " is " & 2012 - cint(line(3))
            foundFlag = True
        End If
    Loop