Populate DataGridView using CSV File

Posted by VIJI Tuesday, April 20, 2010

The following VB.NET Code is used to populate the DataGridView using CSV File.

I have used a 2 dimensional array to store the content of csv row and column wise

Also 2 One dimensional arrays are used to populate the row and column data respectively.

The logic is to parse the file content into string and store in a two dimensional array.

Then read row wise and column wise and populate the DataGridview.

A new DataGridView Row will be created for each line of data and the cells will be populated with the column data.

Private Sub PopulateDataGridViewFromCSV(ByVal SFileName As String)

   'Variables to store the count of rows and columns

   Dim nRows As Long
   Dim nCols As Long

  'Index variables to retrieve the data row wise and col wise

  Dim row As Integer
  Dim col As Integer

'Declaration of Two dimensional array to store the csv content row wise and column wise
Dim ParseArray(1, 1) As String

'Use Try Catch block to handle exceptions

'Check if file exist

If File.Exists(SFileName) Then

   dbGridView.DataSource = Nothing

' Create an unbound DataGridView by declaring a column count.

  dbGridView.ColumnCount = 2
   dbGridView.ColumnHeadersVisible = True
'Set the column header names.
dbGridView.Columns(0).Name = "EmpID"
dbGridView.Columns(1).Name = "Name"

'Open the CSV File into stream

Dim sr As StreamReader = File.OpenText(SFileName)

'Declaration of two single dimensional arrays to store the individual content

Dim RowStringArray() As String
Dim ColStringArray() As String

'Load content of file to RowStringArray array

RowStringArray = sr.ReadToEnd().Split(Environment.NewLine)

'Retrieve the total number of rows
nRows = UBound(RowStringArray)

' Split the content based on "," delimiter

ColStringArray = RowStringArray(0).Split(",")

'Retrieve the total number of columns

nCols = UBound(ColStringArray)

' Redimension the array.

ReDim ParseArray(nRows, nCols)

'Copy the csv content into the 2-dimensional array.

For row = 0 To nRows

ColStringArray = RowStringArray(row).Split(",")

For col = 0 To nCols

ParseArray(row, col) = ColStringArray(col)


Dim dgRow As DataGridViewRow = Nothing

For row = 0 To nRows

dgRow = New DataGridViewRow()

'Add the row

For col = 0 To nCols

dbGridView.Rows(row).Cells(col).Value = ParseArray(row, col)


End If

Catch ex As Exception


End Try
End Sub


PopulateDataGridViewFromCSV ("C:\Test.csv")

will populate the DataGridView With the C:\Test.Csv file.

Sample File: Test.CSV



2 Responses to Populate DataGridView using CSV File

  1. Linus Says:
  2. Hi there, I get an error that dgRow[col] "Expression is not a method". Can you explain?!

    Theank you very much in advance!


  3. Hi Linus,

    Now the issue is solved. Please check now. Also added a sample image to show the output.


Post a Comment