我想输入一个csv文件到Visual Basic数据网格。但是每次我尝试调用一个条目时,它只会读取第一行,目标是读取一个随机行并将该名称输入到列中。从CSV文件读取只返回在Visual Basic中的一行
CSV文件:
Noah,
Liam,
Mason,
Jacob,
William,
Ethan,
James,
Alexander,
Michael,
Benjamin,
Elijah,
Daniel,
Aiden,
Logan,
Matthew,
Lucas,
Jackson,
David,
Oliver,
Jayden,
Joseph,
Gabriel,
Samuel,
Carter,
Anthony,
John,
Dylan,
Luke,
Henry,
Andrew,
Isaac,
Christopher,
Joshua,
Wyatt,
Sebastian,
Owen,
Caleb,
Nathan,
Ryan,
Jack,
Hunter,
Levi,
Christian,
Jaxon,
Julian,
Landon,
Grayson,
Jonathan,
Isaiah,
Charles,
Thomas,
Aaron,
Eli,
Connor,
Jeremiah,
Cameron,
Josiah,
Adrian,
Colton,
Jordan,
Brayden,
Nicholas,
Robert,
Angel,
Hudson,
Lincoln,
Evan,
Dominic,
Austin,
Gavin,
Nolan,
Parker,
Adam,
Chase,
Jace,
Ian,
Cooper,
Easton,
Kevin,
Jose,
Tyler,
Brandon,
Asher,
Jaxson,
Mateo,
Jason,
Ayden,
Zachary,
Carson,
Xavier,
Leo,
Ezra,
Bentley,
Sawyer,
Kayden,
Blake,
Nathaniel,
Ryder,
Theodore,
Elias,
Tristan,
Roman,
Leonardo,
Camden,
Brody,
Luis,
Miles,
Micah,
Vincent,
Justin,
Greyson,
Declan,
Maxwell,
Juan,
Cole,
验证码:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Initialize the random-number generator
DataGridView1.Rows.Clear()
For ix As Integer = 1 To 115
Dim intValue As Integer = CInt(Int((5000 * Rnd()) + 1))
Dim intRandomNumber As Integer
Dim randomName As String = 0
intRandomNumber = (100 * Rnd())
Dim dat(230) As String 'This array holds each item from csv ile
Dim num As Integer = 0
Dim c, p, z As Integer
Dim firstNames(115) As String
Dim blankSpace(115) As Integer
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("firstNames.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
'This section reads the text file into one array dat()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField In currentRow
num = num + 1
dat(num) = currentField
Next
'error reporting
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
p = 0
For c = 1 To num Step 2
p = p + 1
firstNames(p) = dat(c)
Next
End Using
For c = 1 To p
DataGridView1.Rows.Add(Format(ix, "00000"), firstNames(c), "", "", "", intValue)
Next
Next
End Sub
我怀疑你的代码在重复循环之前抛出一个异常。读取文件时,Visual Studio输出窗口中是否显示任何内容? – Dai
另外,'String.Split'对于解析CSV文件并不是一个好的功能,因为它无法处理嵌入在引用字符串中的逗号,例如。 – Dai
您的代码每次都重新打开文件 - 这也是问题的一部分。 – Dai