user2382321
user2382321

Reputation: 105

CSV file to datagridview using list

This is similar to: https://social.msdn.microsoft.com/Forums/en-US/7b0e28b4-c1ef-49d6-8f46-11b379428052/import-from-csv-file-to-two-dimensional-array?forum=vbgeneral

but the code that Cor Ligthert suggests doesn't work even though its exactly what I need.

The code is:

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim FILE_NAME As String = "C:\Users\Admin\Documents\test.csv"

    Dim OutlookLines As New List(Of OutlookLine)
    Dim sr As New IO.StreamReader(FILE_NAME)
    Do Until sr.EndOfStream
        OutlookLines.Add(New OutlookLine With {.line = sr.ReadLine})
    Loop
    DataGridView1.DataSource = OutlookLines

End Sub


Private Class OutlookLine
    Private theLine As String
    Public Property line() As String
        Get
            Return theLine
        End Get
        Set(ByVal value As String)
            theLine = value
        End Set
    End Property
End Class

End Class

I try putting in:

.Split(","c)

after sr.ReadLine but it says "Value of type 1-D array of String cannot be converted to String"

The code above works fine but each row of the csv is scrunched into one column (obviously because I am not splitting it at the ",").

csv data:

1,2,3,4,5
6,7,8,9,0

Upvotes: 0

Views: 600

Answers (2)

Craig Johnson
Craig Johnson

Reputation: 754

See if this works for you:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DataGridView1.DataSource = CSVToDataTable("C:\Users\Admin\Documents\test.csv", True)
End Sub

Private Function CSVToDataTable(filePath As String, Optional hasHeaderRow As Boolean = False) As DataTable
    Dim rows = IO.File.ReadAllLines(filePath).Select(Function(l) l.Split(","c))

    Dim dt = New DataTable
    Dim count = 0

    dt.Columns.AddRange(rows.First.Select(Function(c) New DataColumn With {.ColumnName = If(hasHeaderRow, c, "Column" & Threading.Interlocked.Increment(count))}).ToArray())

    For Each row In rows.Skip(If(hasHeaderRow, 1, 0))
        Dim dr = dt.NewRow()
        dr.ItemArray = row
        dt.Rows.Add(dr)
    Next

    Return dt
End Function

Upvotes: 1

NoAlias
NoAlias

Reputation: 9193

If you wish for the line property of the OutlookLine class to be an array of string, you should define it like this:

Private Class OutlookLine
    Private theLine As String()
    Public Property line As String()
        Get
            Return theLine
        End Get
        Set(ByVal value As String())
            theLine = value
        End Set
    End Property
End Class

Then this will work:

        OutlookLines.Add(New OutlookLine With {.line = sr.ReadLine.Split(",")})

Upvotes: 0

Related Questions