【发布时间】:2019-01-14 11:24:35
【问题描述】:
我正在尝试从 csv 文件在数据网格上打印,但在 PhNumber 列上出现“System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'”错误。当我删除此列时,错误将移至“年龄”列。我在这里到底做错了什么?我认为这是我编写 csv 的方式有误,但我检查了一千次,我找不到任何东西。
Vannessa Sanchez,23,Physics Methods Specialist,85.30,44 Garden Place KURRACA WEST Victoria 3518,(03) 9270 3392
Usnavi de la Vega,29,Biology Chemistry,90.55,66 Hebbard Street KNOXFIELD Victoria 3180,(03) 9270 3392
Benny Smith,24,Physics,88.35,31 Cambridge Street MULGRAVE Victoria,(03) 4745 6684
Nina Rosario,20,English History,88.75,96 Boughtman Street FERNTREE GULLY Victoria 3156,(03) 9293 4908
Alexander Hamilton,40,English,82.45,40 South Street HASTINGS Victoria 3915,03 5550 0388
Thomas Jefferson,32,French English,92.95,69 Parkes Road DANDENONG Victoria 3004,(03) 8694 7835
John Adams,57,Chemistry Methods,84.25,25 Hodgson St CLAYTON Victoria 3168,(03) 4560 8693
Eliza Schuyler,31,Physics Methods,94.95,68 Weigall Avenue OAKLEIGH VICTORIA 3166,(03) 8395 6353
Public Class Form1
Dim TutorTable As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With TutorTable
.Columns.Add("Name", System.Type.GetType("System.String"))
.Columns.Add("Age", System.Type.GetType("System.String"))
.Columns.Add("Subjects", System.Type.GetType("System.String"))
.Columns.Add("ATAR", System.Type.GetType("System.String"))
.Columns.Add("Location", System.Type.GetType("System.String"))
.Columns.Add("PhNumber", System.Type.GetType("System.String"))
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Reader As New IO.StreamReader("D:\Users\user\Downloads\TutorData.csv", System.Text.Encoding.Default)
Dim StringLine As String = ""
Do
StringLine = Reader.ReadLine
If StringLine Is Nothing Then Exit Do
Dim Columns() As String = StringLine.Split(",")
Dim NewRow As DataRow = TutorTable.NewRow
NewRow("Name") = Columns(0)
NewRow("Age") = Columns(1)
NewRow("Subjects") = Columns(2)
NewRow("ATAR") = Columns(3)
NewRow("Location") = Columns(4)
NewRow("PhNumber") = Columns(5)
TutorTable.Rows.Add(NewRow)
Loop
Reader.Close()
DataGridView1.DataSource = TutorTable
Me.Text = TutorTable.Rows.Count & "rows"
End Sub
【问题讨论】:
-
你试过调试你的程序吗?专栏的内容是什么?在
Dim NewRow As DataRow = TutorTable.NewRow行设置断点并告诉我们。 -
您提供的代码示例和数据对我来说绝对没问题。
-
您确定您的所有数据都没有缺少逗号吗?
-
BTW 提出了一个结构良好的问题,因此我们可以尝试重现正在发生的事情。
-
当您的代码挂起时,将鼠标悬停在
Dim Columns() As String = StringLine.Split(",")行中的 Columns 数组上,以查看数组中有多少元素。