在Visual Basic中选择列表框项时错误切换CVS文本文件项

时间:2012-11-14 18:35:26

标签: vb.net text csv if-statement listbox

我正在尝试将“M”切换为“Mr.”和“F”到“女士”在列表框中选择姓氏时。当我点击它的第一个名称时,但是当我点击任何其他名称时,我收到此错误消息:

- 附加信息:索引超出了数组的范围.--

文本文件中的信息如下:

       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

我的代码如下:

    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

有人可以让我知道什么是错的。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我重新创建了你的应用程序,就像你在这里完成一样,并且工作正常。

这让我相信发生了两件事之一:

  1. 您的Info.txt档案
  2. 中有不良字符
  3. 您尚未使用与lstNames中相同的名称填充Info.txt组合框。
  4. PS - 您可能还想查看循环以提高效率:

        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