How to Read a Csv File in Visual Basic

Written by kevin walker
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Read a Csv File in Visual Basic
(George Doyle/Stockbyte/Getty Images)

Comma Separated Value (CSV) format is a common format used to exchange data between different programs that may not support each other's native format. For example, it can be used to exchange spreadsheet data between Excel and another spreadsheet, or database data between Access and MySQL. Visual Basic does not contain an automatic function for loading CSV files, however one of the reasons for its widespread support is its simplicity. As the name implies, CSV files are nothing but a list of values, each separated by a comma or a new line. It is fairly simple to create a CSV reader in Visual Basic.

Skill level:


  1. 1

    Create a new project by clicking "File" and "New Project."

  2. 2

    Drag a button onto your form from the toolbox using your mouse.

  3. 3

    Find the "OpenFileDialog" control and add it to your form as well. Since this control is initially invisible, it will not appear on your form, but rather beneath it.

  4. 4

    Double-click on the button to create an event that will occur whenever the user clicks the button. Paste the following code that will ask the user for a CSV file and load its data into a 2D array:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    	REM Get the file the user wants to load.
        Dim filename As String = OpenFileDialog1.FileName
        Dim file Stream As System.IO.StreamReader = New System.IO.StreamReader(filename)

    REM Read all the data from the file into a single string. Dim contents As String = fileStream.ReadToEnd

        REM Split the string into its values. After this operation is finished, there will be a one dimensional array of values, and the end of the rows will be marked by empty strings.
        Dim values = contents.Split()
        Dim arr As ArrayList = New ArrayList
        Dim rows As ArrayList = New ArrayList

    REM Move the data into a 2D array. For x As Integer = 0 To lines.Length - 1 If lines(x) IsNot String.Empty Then arr.Add(lines(x)) End If rows.Add(arr.Clone) arr.Clear() Next

        Dim data(rows.Count, rows(0).count) As String
        For x As Integer = 0 To rows.Count - 1
            For y As Integer = 0 To rows(x).count - 1
                data(x, y) = rows(x)(y)
    End Sub

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.