Header Ads

Populate DataGridView using CSV File

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
Try
  'Check if file exist
   If File.Exists(sFileName) Then
  '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)
     Next
   Next
   'Display the data in ListBox
    Dim dgRow As DataGridViewRow
    For row = 0 To nRows
   For col = 0 To nCols
         dgRow = new DataGridViewRow()
        dgRow[col] = ParseArray(row,col)                 
   
   Next
      'Add the row
      dbGridView.Rows.Add(dgRow)
 Next
End If
Catch ex As Exception
  MessageBox.Show(ex.Message)
End Try
End Sub

No comments:

Powered by Blogger.