65.9K
CodeProject is changing. Read more.
Home

Load datagridview from CSV or TXT File

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (5 votes)

May 22, 2014

CPOL
viewsIcon

14101

A simple code that loads a daagridview from a textfile

Introduction

This tip shows you how to load a datagridview from a simple CSV file or text file.

Using the Code

We work with a simple sub that opens a window (with OpenFileDialog) for choosing the file into PC or other devices.

Example of file:

ID;Customer;City;Category
1;Rossi;Milan;Food
2;Verdi;Rome;Food
3;Black;Venice;Food
4;Yellow;Florence;Drink
5;Purple;Naples;Drink 
        OpenFileDialog1.Filter = "txt files|; *.txt"
        OpenFileDialog1.Title = "Select a txt file"
        OpenFileDialog1.FileName = ""

        Try
            With OpenFileDialog1
                If .ShowDialog() = DialogResult.OK Then
                    FileName = .FileName
                 

                    Dim myDataT As DataTable = BuildDataTable(FileName, ";")
                    ds = New DataSet()
                    ds.Tables.Add(myDataT)
                    grdBarcode.DataSource = myDataT


                    Dim numberofrows As Integer = grdBarcode.RowCount - 1
                    MessageBox.Show(numberofrows & " rows were 
                    loaded into the datagridview", "", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End If
            End With

        Catch
        End Try 

Then after select file, the sub with the command:

 Dim myDataT As DataTable = BuildDataTable(FileName, ";")  

Run a function that loads the data (stored into file) and return a datatable:

Dim DTable As DataTable = New DataTable("Barcode")
        Dim i As Integer
        Dim myRow As DataRow
        Dim fieldValues As String()
        Dim f As IO.File = Nothing
        Dim myReader As New IO.StreamReader(fileFullPath, System.Text.Encoding.UTF8)  
        Try
            fieldValues = myReader.ReadLine().Split(separator)
            
            For i = 0 To fieldValues.Length() - 1
                
                DTable.Columns.Add(New DataColumn(fieldValues(i)))
            Next
            
            While myReader.Peek() <> -1
                fieldValues = myReader.ReadLine().Split(separator)
                myRow = DTable.NewRow
                For i = 0 To fieldValues.Length() - 1
                    myRow.Item(i) = fieldValues(i).ToString
                Next
                DTable.Rows.Add(myRow)
            End While
        Catch ex As Exception
            MsgBox("Error building datatable: " & ex.Message)
            Return New DataTable("EmptyDTable")
        Finally
            myReader.Close()
        End Try

        Return DTable
    End Function

When the function has finished, the datatable is complete and is ready to be loaded into datagrid.

grdBarcode.DataSource = myDataT 

In this case, my datagrid name is "grdBarcode".