我正在尝试将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
答案 0 :(得分:0)
以下方法将从文件中返回指定数量的随机行:
'Random number generator.
Private rng As New Random
Private Function GetRandomLines(filePath As String, lineCount As Integer) As String()
Return IO.File.ReadAllLines(filePath).
OrderBy(Function(s) rng.NextDouble()).
Take(lineCount).
ToArray()
End Function
您可以调用该方法,然后遍历结果,拆分和加载。如果您只想要一行而不是多行,那么您只需拨打First
或FirstOrDefault
并返回String
而不是数组。
关于拆分数据,如果它可能包含包含逗号的带引号的字段值,最好使用TextFieldParser
。问题在于你必须先拆分每一行才能知道有多少行,这意味着多余的工作。