2012-04-05 85 views
0

我一直在嘗試運行了一個程序,在一個列表框點擊的東西時,收到此錯誤。的Visual Basic - IndexOutOfRangeException錯誤

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。兩個都是數字。

+0

「調試我的代碼爲我」的問題是沒有真正的話題在這裏。 – 2012-04-05 04:36:18

+0

爲什麼你會寫一個文件,然後從文件中讀取?爲什麼不把它加載到數據表中?即使你確實需要一個文件,將它加載到一個表中,寫入文件並從表中讀取。 – Jesse 2012-04-05 06:10:06

回答

0

我偶爾遇到此問題與List.SelectedIndex_changed事件。在selectedItem改變之間,即使未選擇任何項目,此代碼也會被觸發。我的解決方案是在開始時檢查它是否有效。

If ListBox1.SelectedItems.Count = 0 then exit sub