Hi guys,
Could you teach me how to read CSV in listview using OpenFileDialog?
I'm using VB 2010

Thank's a lot

Edited 3 Years Ago by McGreedy

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

    Dim ofd As New OpenFileDialog
    If ofd.ShowDialog = Windows.Forms.DialogResult.OK AndAlso ofd.FileName <> "" Then
            Using reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(ofd.FileName)
                reader.TextFieldType = FileIO.FieldType.Delimited
                While Not reader.EndOfData
                    Dim Fields() As String = reader.ReadFields
                    Dim item As New ListViewItem
                    item.Text = Fields(0)
                    For x = 1 To UBound(Fields)
                End While
            End Using
        Catch ex As Exception
        End Try
    End If
    **ListView1.AutoResizeColumn(0, ColumnHeaderAutoResizeStyle.ColumnContent)**

End Sub

I've been tried but still no work the program sent me error report
"InvalidArgument=Value of '1' is not valid for 'columnIndex'.
Parameter name: columnIndex"

I've 32 columns at my .csv files

Edited 3 Years Ago by McGreedy

When you get the error in the error window at the bottom it should report the line number with the error. That's the code we need to see.

Here's a simple example of code you can use, you'll have to import System.IO

        'Read the file an put each line into a list.  Each line will be an item with subitems in the listview
        CSVTest = File.ReadAllLines("C:\test.csv").ToList

        'This adds the column headers.  If the first line of your file isn't header text, just use a comma delimeted string of the text that you want.
        Dim ColNames As List(Of ColumnHeader) = New List(Of ColumnHeader)

        'Replace `CSVTest(0)` with your new string if necessary.
        Dim ColumnArray() As String = CSVTest(0).Split(",")
        For i = 0 To ColumnArray.Count - 1
            ColNames.Add(New ColumnHeader)
            ColNames(i).Name = ColumnArray(i)
            ColNames(i).Text = ColumnArray(i)

        'This adds the rest of the data from the file to the listview.  If the first line of the file is data and not header text, then change `For I = 1 To CSVTest.Count - 1` to `For I = 0 To CSVTest.Count - 1`
        For I = 1 To CSVTest.Count - 1
            Dim col() As String = CSVTest(I).Split(",")
            Dim NewLVItem As ListViewItem = New ListViewItem(col(0))
            NewLVItem.Name = col(0)
            For j = 1 To col.Count - 1

Edited 3 Years Ago by tinstaafl

This article has been dead for over six months. Start a new discussion instead.