Click here to Skip to main content
14,743,899 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
as the title suggest i need to insert the CSV into a single column in DataTable.


the datatable should be:
and so on..
this is my code.

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

If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim sr As New IO.StreamReader(OpenFileDialog1.FileName)
Dim dt As New DataTable

dt.Columns.AddRange({New DataColumn(newline(0)),
New DataColumn(newline(1))})

While (Not sr.EndOfStream)
newline = sr.ReadLine.Split("-"c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1)}

End While
DataGridView1.DataSource = dt
End If

What I have tried:

i tried editing the " dt.Columns.AddRange({New DataColumn(newline(0))}) " thinking it has something to do with newline (1) but no go.
Updated 23-Nov-20 1:59am

1 solution

First off, that's not CSV - it stands for "Comma Separated Values" and strictly, that isn't separated by commas, it uses hyphens instead.
And the other problem is that CSV is organised into rows of columns, and you appear rto not be doing that at all.

Instead, I'd just read it as text, and use Split to "break it up". You can then use the result to populate your DGV directly:
Dim data As String = File.ReadAllText("D:\Test Data\AAAData.csv")
Dim parts As String() = data.Split("-"c, vbLf)
Dim viewable = parts.[Select](Function(p) New With {Key.Value = p}).ToList()
dataGridView1.DataSource = viewable

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900