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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43974213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:16:52  来源:igfitidea点击:

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

vb.netdatagridviewcsv-import

提问by K. Arth

My used code is:

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

My output looks wrongly encoded: enter image description here

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

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

回答by K. Arth

This is really work!

This is really work!

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(txtpathfile.Text, Encoding.ASCII)
        Do While objReader.Peek() <> -1
            TextLine = objReader.ReadLine()
            SplitLine = Split(TextLine, ";")
            Me.DataGridView1.Rows.Add(SplitLine)
        Loop
    Else
        MsgBox("File Does Not Exist")
    End If