Decoder94 February 2016

How to add csv file in a 2d array vb.net?

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

Joe, 34,3,32,1,3

John, 32,2

Tom, 98,34,23

Dave, 56, 53, 32,1,22,6,5

I have this csv file that I would like to put in a 2d array.

Private Sub GetElement()
    'Read the data from the cv file
    Try
        Dim fileIn As String = "mel.csv"
        Dim fileRows(), fileFields() As String
        Dim count As Integer = 0
        textBox.Text = String.Empty
        If File.Exists(fileIn) Then
            Dim fileStream As StreamReader = File.OpenText(fileIn)
            fileRows = fileStream.ReadToEnd().Split(Environment.NewLine)
            For i As Integer = 0 To fileRows.Length - 1
                fileFields = fileRows(i).Split(",")
                If fileFields.Length >= 2 Then
                    For x As Integer = 0 To fileFields.Length - 1
                        If x = 0 Then
                            For e As Integer = 0 To fileFields.Length
                                ele.Add(fileFields(e))
                                listBox.Items.Add(ele(e))
                            Next
                        End If
                    Next
                    count = count + 1
                End If
            Next
        Else
            textBox.Text = fileIn & " not found."
        End If
    Catch ex As Exception
        textBox1.Text = ex.Message
    End Try
End Sub

I was able to receive the first line only and then I have added it to a list box. In the MainWindow class I have declared two list of string to store the column and rows.

Answers


Ayman Eljahrani February 2016

Why don't you work with objects since you are working with an OO'programing language . It would be simple and more optimised if you created a new class . And then create a new object after reading each line . Dim u as new User(x,y,z...) And to organise your data, use a hashtable or a linkedlist (don't know if it's called like this for vb.net). Then you can fill in your listbox from objects that are in your hashtable or linkedlist.


Monty February 2016

try this....

Imports System.Data.OleDb

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim folder = "Path to your CSV folder (do not include the file name here)"
    Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
    Dim dt As New DataTable
    ' change Test.csv to your csv file name here
    Using Adp As New OleDbDataAdapter("select * from [Test.csv]", CnStr)
        Try
            Adp.Fill(dt)
        Catch ex As Exception
        End Try
    End Using

    DataGridView1.DataSource = dt
End Sub

End Class

this will import the CSV file then display it straight into a DataGridView control (list box has problem with columns)... hope that helps

Post Status

Asked in February 2016
Viewed 2,469 times
Voted 6
Answered 2 times

Search




Leave an answer