Visual Basic - IndexOutOfRangeException错误

时间:2012-04-05 02:02:17

标签: vb.net exception indexing range

尝试运行程序并单击列表框中的某些内容时,我一直收到此错误。

IndexOutOfRangeException未处理 索引超出了数组的范围。

我的代码及其错误的部分(标记为><):

            Dim conn As MySqlConnection
    conn = New MySqlConnection("server=db4free.net;port=3306; user id=*******; password=**********; database=*******")

    Dim sqlquery As String = "SELECT * FROM UTGAccess"
    Dim adapter As New MySqlDataAdapter
    Dim data As MySqlDataReader
    Dim command As New MySqlCommand
    conn.Open()
    command.CommandText = sqlquery
    command.Connection = conn
    adapter.SelectCommand = command
    data = command.ExecuteReader
    While data.Read()
        ListBox1.Items.Add(data(1).ToString)
        ListBox3.Items.Add(data(0).ToString)
        Dim writer As New System.IO.StreamWriter(My.Application.Info.DirectoryPath + "/" + data(1).ToString + "=" + data(0).ToString + ".txt", False)
        writer.Write(data(3).ToString + "=" + data(0).ToString)
        writer.Close()
    End While

    data.Close()
    conn.Close()

End Sub

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    ListBox3.SelectedIndex = ListBox1.SelectedIndex
    Dim reader As New System.IO.StreamReader(My.Application.Info.DirectoryPath + "/" + ListBox1.SelectedItem.ToString + "=" + ListBox3.SelectedItem.ToString + ".txt")
    Dim splitread() As String = reader.ReadToEnd.Split("=")
    reader.Close()
  > lbl_rank1.Text = "Rank: " + splitread(3).ToString  <
    lbl_id1.Text = "ID: " + splitread(0).ToString
End Sub

请注意,它不会在lbl_id1.text上出错,但会在lbl_rank1.text上出错。 ID是网站上的INT,而排名是VARCHAR。两者都是数字。

1 个答案:

答案 0 :(得分:0)

我偶尔会遇到List.SelectedIndex_changed事件的这个问题。在selectedItem更改之间,即使没有选择任何项,此代码也会被触发。我的解决方案是在开头检查它是否有效。

If ListBox1.SelectedItems.Count = 0 then exit sub