Road King
Road King

Reputation: 147

Working with commas in a comma delimited file

I have a vb project that imports a csv file and some of the data contains commas. The fields with the commas are in double quotes.

I am creating a datagridview from the header row of the csv then importing the remainder of the file into the dgv but the fields with commas are causing a problem. The fields are not fixed width.

I think I need a way to qualify the commas as a delimiter based on double quote or some other method of importing the data into the dgv.

Thanks

Using objReader As New StreamReader(FName)
Dim line As String = objReader.ReadLine()
Do While objReader.Peek() <> -1
    line = objReader.ReadLine()
    Dim splitLine() As String = line.Split(",")
    DataGridView1.Rows.Add(splitLine)
    Application.DoEvents()
Loop
End Using

Example Data:

1,"VALIDFLAG, NOGPS",0,1.34,3.40,0.17,1

Upvotes: 1

Views: 2009

Answers (1)

Road King
Road King

Reputation: 147

Thinks very much for the suggestions.

I am going to use textfieldparser for my import.

Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(FName)
    MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
    MyReader.Delimiters = New String() {","}
    Dim currentRow As String()
    Dim firstline As Boolean = True
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.ReadFields()
            If firstline = True Then
                firstline = False
            Else
                Me.DataGridView1.Rows.Add(currentRow)
            End If
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & " is invalid.  Skipping")
        End Try
        Application.DoEvents()
    End While
End Using

Upvotes: 2

Related Questions