在读取文本文件时,索引超出了vb.net中数组的范围

时间:2017-12-01 03:06:41

标签: vb.net

我有一段文字,其中包含1928年至2014年的奥斯卡电影列表。我使用数组查找电影的名称并将其放入一个文本框中,然后将其放入下一个文本框中。该类型是电影名称的旁边。我试图分别访问这两个并将其放入两个不同的文本框中。

我的代码:

Dim mvs(86) As Movie

Private Sub FrmAcademy_Load() Handles MyBase.Load
    Dim mviLine As String
    Dim mviData(1) As String
    Dim allMovies() As String = IO.File.ReadAllLines("Oscars.txt")

    For mviList As Integer = 0 To 86
        mviLine = allMovies(mviList)
        mviData = mviLine.Split(","c)
        mvs(mviList).mviName = mviData(0)
        mvs(mviList).gnrName = mviData(1)

        Dim mviYear As Integer = 0
        Dim mviIndex As Integer = 0

        If (IsNumeric(txtAwards.Text)) = True Then
            mviYear = CInt(txtAwards.Text)
        End If

        If (mviYear >= 1928) Or (mviYear <= 2014) Then
            mviIndex = 1928 - mviYear
            txtFilm.Text = mvs(mviIndex).mviName
            txtGenre.Text = mvs(mviIndex).mviName
        End If
    Next
End Sub

Private Sub btnPicture_Click(sender As Object, e As EventArgs) Handles btnPicture.Click
    If (IsNumeric(txtAwards.Text)) = False Then
        MessageBox.Show("Please enter a year as a numeric value")
    ElseIf CInt(txtAwards.Text) > 2014 Then
        MessageBox.Show("Please choose a year in range")
    ElseIf CInt(txtAwards.Text) < 1928 Then
        MessageBox.Show("Please choose a year in range")
    End If

2 个答案:

答案 0 :(得分:0)

不应该是:

If (mviYear >= 1928) And (mviYear <= 2014) Then
    mviIndex = mviYear - 1928

答案 1 :(得分:0)

要获得更好的帮助,至少要花时间正确格式化代码。

您的mvs数组已声明,但每个元素的初始化位置是什么?

For循环的第一行,添加以下代码:mvs(mviList) = New Movie()