Vb.net – Populate DataGridView with CSV file excluding the Header Record

csvdatagridviewvb.net

The below code imports my CSV file into the data grid. Only issue is it populates the header with a row from the CSV file, I want the header to be left blank and rows to be imported after it. Please advise.

        If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then


        Dim fi As New FileInfo(OpenFileDialog1.FileName)
        Dim sConnectionStringz As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
        Dim objConn As New OleDbConnection(sConnectionStringz)
        objConn.Open()
        'DataGridView1.TabIndex = 1
        Dim objCmdSelect As New OleDbCommand("SELECT * FROM " & fi.Name, objConn)
        Dim objAdapter1 As New OleDbDataAdapter
        objAdapter1.SelectCommand = objCmdSelect
        Dim objDataset1 As New DataSet
        objAdapter1.Fill(objDataset1, "test")
        '--objAdapter1.Update(objDataset1) '--updating
        DataGridView1.DataSource = objDataset1.Tables(0).DefaultView

        objConn.Close()
    End If

Best Solution

Two ideas come to mind, simply blank out the header cells when columns are added in grid_ColumnAdded event handler

  if e.Column.HeaderText = "YourColumnHeaderText" Then        
     e.Column.HeaderText = String.Empty;

Or it maybe easier to read the CSV file with a streamreader, ref: http://www.dotneter.com/import-csv-file-into-datagridview (note I'd load into a Datatable rather than populate the Grid directly):

Dim streamReader As System.IO.StreamReader = New StreamReader(txtPath.Text)

'Reading CSV file header
rowValue = streamReader.ReadLine()
cellValue = rowValue.Split(","C)
Dim i As Integer = 0
While i <= cellValue.Count() - 1
    Dim column As New DataGridViewTextBoxColumn()
    column.Name = cellValue(i)
    column.HeaderText = cellValue(i)
    dataGridView1.Columns.Add(column)
    i += 1
End While

'Reading CSV file content
While streamReader.Peek() <> -1
    rowValue = streamReader.ReadLine()
    cellValue = rowValue.Split(","C)
    dataGridView1.Rows.Add(cellValue)
End While

The last idea was deleting a row from the datatable before assigning to the Grids datasource: http://msdn.microsoft.com/en-us/library/feh3ed13(v=vs.80).aspx

objDataset1.Tables(0).Rows[0].Delete();