我試圖從文本文件顯示信息到多行文本框中。我運行代碼,但系統顯示錯誤消息'索引超出了數組的範圍'。沒有明顯的錯誤消息,我似乎無法操縱代碼來擺脫此問題。看一看:我不斷收到和錯誤消息'索引超出了數組的範圍'
Public Class TeachCon
Dim layout As String
Dim Contacts(6) As Details
Structure Details
Dim Name As String
Dim Email As String
Dim RoomNum As String
Dim number1, number2 As Integer
End Structure
Sub LoadTeachContacts(ByRef Contacts() As Details)
Dim TextFile As String = "\\Sjcdom01\mstudent\LHeywood\documents\A2\Computing\Comp 4 - Smail\Project\Text Files\Teacher Contact List.txt"
Dim TextLine As String = ""
Dim ArrayCounter As Integer = 0
Dim objReader As New System.IO.StreamReader(TextFile)
'loop through text file and load all contacts
Do While objReader.Peek() <> -1
'read next line from file
TextLine = TextLine & objReader.ReadLine() & vbNewLine
'declare an array and use it to split line from file
Dim TempArray() As String = Split(TextLine, ",")
'transfer each array element into the appropriate part of the contacts stucture
Contacts(ArrayCounter).Name = TempArray(0)
*Contacts(ArrayCounter).Email = TempArray(1)*
Contacts(ArrayCounter).RoomNum = TempArray(2)
Contacts(ArrayCounter).number1 = TempArray(3)
Contacts(ArrayCounter).number2 = TempArray(4)
'empty string before reading next line from file
TextLine = ""
'increment array counter
ArrayCounter = ArrayCounter + 1
Loop
End Sub
Private Sub ButShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim ArrayCounter As Integer = 0
LoadTeachContacts(Contacts)
Do Until ArrayCounter = 3
layout = Contacts(ArrayCounter).Name & "," & Contacts(ArrayCounter).Email & "," & Contacts(ArrayCounter).RoomNum & "," & Contacts(ArrayCounter).number1 & "," & Contacts(ArrayCounter).number2
If ArrayCounter = 0 Then
TextBox7.Text = layout
End If
ArrayCounter += 1
Loop
End Sub
End Class
*所包含的文本是系統表示它位於數組邊界之外的地方。
該數組有7個元素。文本文件有多大的可能性?好吧,我想象的是大概100%。改爲使用「List(Of Details)」。當Split()產生一個太小的數組時,你必須跳過空行並大叫。使用TempArray.Length來檢查。 – 2015-03-31 10:00:59
該文本文件目前有三行,每行有5項數據 – LMH 2015-03-31 11:44:42