我想輸入一個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