Visual Basic - IndexOutOfRangeException Error

Go To StackoverFlow.com

0

I keep getting this error when trying to run my program and click on something in a listbox.

IndexOutOfRangeException was unhandled Index was outside the bounds of the array.

My Code and the part where it errors (Marked with ><):

            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

Note that it doesn't error on lbl_id1.text but it does on lbl_rank1.text. The ID is an INT on the site, while the rank is a VARCHAR. Both are numbers.

2012-04-05 02:02
by FtDLulz
"Debug my code for me" questions are not really on-topic here - Cody Gray 2012-04-05 04:36
Why would you write to a file and then read from the file? Why not load it into a datatable? Even if you do want a file, load it to a table, write the file and read from the table - Jesse 2012-04-05 06:10


0

I occassionally run into this problem with the List.SelectedIndex_changed event. Between the selectedItem changing, this code gets fired, even when no item is selected. My solution is to put a check at the beginning to see if it is valid or not.

If ListBox1.SelectedItems.Count = 0 then exit sub
2012-04-05 11:57
by APrough
Ads