Click here to Skip to main content
16,012,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have datagrid that have header already, so I want to populate inside the datatable without changing header

I'm using this method to import data from csv.

What I have tried:

Private Sub Open_Click(ByVal sender As Object, ByVal e As EventArgs)
    openFileDialog1.ShowDialog()
    txtFile.Text = openFileDialog1.FileName
    BindData(txtFile.Text)
End Sub

Private Sub BindData(ByVal filePath As String)
    Dim dt As DataTable = New DataTable()
    Dim lines As String() = System.IO.File.ReadAllLines(filePath)

    If lines.Length > 0 Then
        Dim firstLine As String = lines(0)
        Dim headerLabels As String() = firstLine.Split(","c)

        For Each headerWord As String In headerLabels
            dt.Columns.Add(New DataColumn(headerWord))
        Next

        For i As Integer = 1 To lines.Length - 1
            Dim dataWords As String() = lines(i).Split(","c)
            Dim dr As DataRow = dt.NewRow()
            Dim columnIndex As Integer = 0

            For Each headerWord As String In headerLabels
                dr(headerWord) = dataWords(Math.Min(System.Threading.Interlocked.Increment(columnIndex), columnIndex - 1))
            Next

            dt.Rows.Add(dr)
        Next
    End If

    If dt.Rows.Count > 0 Then
        dataGridView1.DataSource = dt
    End If
End Sub
Posted
Updated 31-Mar-20 7:58am

1 solution

At the first look you need to change DataGridView.AutoGenerateColumns Property (System.Windows.Forms) | Microsoft Docs[^] and set it to False.

Follow the link for further details.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900