简体   繁体   English

从CSV文件读取仅在Visual Basic中返回一行

[英]Reading from CSV file only returns one line in Visual Basic

I am trying to input a csv file into a Visual Basic Data Grid. 我试图将一个csv文件输入到Visual Basic数据网格中。 But each time I try to call an entry it only reads the first Line, The goal is to read a random line and input the name into the Column. 但是每次我尝试调用一个条目时,它只会读取第一行,目标是读取一条随机行并将名称输入到列中。

The CSV File: 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,

The Code: 编码:

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

The following method will return a specified number of random lines from a file: 以下方法将从文件返回指定数量的随机行:

'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

You can call that method and then loop through the results, splitting and loading. 您可以调用该方法,然后遍历结果,拆分和加载。 If you only want one line rather than multiple then you can just call First or FirstOrDefault and return a String instead of an array. 如果只想一行而不是多行,则可以只调用FirstFirstOrDefault并返回一个String而不是一个数组。

With regards to splitting the data, it would be preferable to use a TextFieldParser if it might contain quoted field values that contain commas. 关于拆分数据,如果TextFieldParser可能包含带逗号的引号字段值,则最好使用TextFieldParser The problem with that is that you would have to split every line before you could know how many there are, which means redundant work. 这样做的问题是,您必须先拆分每一行,然后才能知道有多少行,这意味着多余的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM