Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading csv file doesn't show anything?

I am a beginner in visual basic and trying to import csv file into datagridview.

The sample code I used is as follows:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

  Using MyReader As New Microsoft.VisualBasic.
                FileIO.TextFieldParser("C:\test\text.txt")
    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Application.DoEvents()
        Try
            currentRow = MyReader.ReadFields()
            With DataGridView1
                .ColumnCount = 2
                Dim row As String() = New String() {currentRow(0), currentRow(1)}
                .Rows.Add()
            End With
        Catch ex As Microsoft.VisualBasic.
                    FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    End While
  End Using
End Sub

The data I am using is as follows:

Date,distance
1,5
2,8
4,9
10,15

However, I am getting blank datagridview after I import the csv file using above code.

The output looks like:

enter image description here

like image 420
Jd Baba Avatar asked Mar 01 '26 12:03

Jd Baba


1 Answers

With the following code

With DataGridView1
    ...
    .Rows.Add()
End With

you create an empty row by calling Add without any parameters.

You probably want to call

.Rows.Add(row)
like image 89
sloth Avatar answered Mar 03 '26 07:03

sloth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!