.CSV to DataGridView Rows coming up blank in VB.NET

后端 未结 2 1540
误落风尘
误落风尘 2021-01-26 05:04

Here is the CSV data I am trying to import into my VB.NET app:

Raw Data

But when I run it through the app it only populates the last row:

Output

2条回答
  •  生来不讨喜
    2021-01-26 05:31

    I would not suggest trying to read the data via a StreamReader, instead use the OleDb class while passing the connection string for a CSV file.

    Here is a quick example of a function that returns a DataTable based on the contents of the CSV file:

    Private Function ConvertCSVToDataTable(ByVal path As String) As DataTable
        Dim dt As DataTable = New DataTable()
        Using con As OleDb.OleDbConnection = New OleDb.OleDbConnection()
            Try
                con.ConnectionString = String.Format("Provider={0};Data Source={1};Extended Properties=""Text;HDR=YES;FMT=Delimited""", "Microsoft.Jet.OLEDB.4.0", IO.Path.GetDirectoryName(path))
                Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM " & IO.Path.GetFileName(path), con)
                    Using da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(cmd)
                        con.Open()
                        da.Fill(dt)
                        con.Close()
                    End Using
                End Using
            Catch ex As Exception
                Console.WriteLine(ex.ToString())
            Finally
                If con IsNot Nothing AndAlso con.State = ConnectionState.Open Then
                    con.Close()
                End If
            End Try
        End Using
    
        Return dt
    End Function
    

    Then here is how you'd bind your DataGridView:

    DataGridView1.DataSource = Me.ConvertCSVToDataTable(ofd.FileName)
    

    Update

    Since you want to specify the data type of the DataColumn, declare a DataTable and assign it to the custom function, but then go in after the fact and change the data type of the specific columns. Here is a quick (free-typed and untested) example:

    Dim csv As DataTable = Me.ConvertCSVToDataTable(ofd.FileName)
    With csv.Columns
        .Items(0).DataType = GetType(Int32)
        .Items(1).DataType = GetType(Int32)
        .Items(4).DataType = GetType(Int32)
        .Items(5).DataType = GetType(Int32)
    End With
    
    DataGridView1.DataSource = csv
    

提交回复
热议问题