How to import .csv file to my datagridview in vb.net?

K. Arth picture K. Arth · May 15, 2017 · Viewed 11.6k times · Source

My used code is:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim fName As String = ""
    OpenFileDialog1.InitialDirectory = "c:\desktop"
    OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
    OpenFileDialog1.FilterIndex = 2
    OpenFileDialog1.RestoreDirectory = True
    If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
        fName = OpenFileDialog1.FileName
    End If
    txtpathfile.Text = fName
    Dim TextLine As String = ""
    Dim SplitLine() As String

    If System.IO.File.Exists(fName) = True Then
        Dim objReader As New System.IO.StreamReader(fName)
        Do While objReader.Peek() <> -1
            TextLine = objReader.ReadLine()
            SplitLine = Split(TextLine, ",")
            Me.DataGridView2.Rows.Add(SplitLine)
        Loop
    Else
        MsgBox("File Does Not Exist")
    End If
End Sub

My output looks wrongly encoded: enter image description here

What's wrong with my code? Please help me. Thank you for consideration.

Answer

Trexer picture Trexer · Nov 12, 2020

I arrived here from google. Just in case someone sarching for a quick code to copy:

    Private Sub ReadCSV()
        Dim fName As String = "C:\myfile.csv"
        Dim TextLine As String = ""
        Dim SplitLine() As String

        If System.IO.File.Exists(fName) = True Then
            Using objReader As New System.IO.StreamReader(fName, Encoding.ASCII)
                Do While objReader.Peek() <> -1
                    TextLine = objReader.ReadLine()
                    SplitLine = Split(TextLine, ";")
                    Me.DataGridView1.Rows.Add(SplitLine)
                Loop
            End Using
        Else
            MsgBox("File Does Not Exist")
        End If
    End Sub