Results 1 to 5 of 5

Thread: [RESOLVED] Removing first row (headers) of a dgv to a csv file

  1. #1

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    381

    Resolved [RESOLVED] Removing first row (headers) of a dgv to a csv file

    Following code will create a csv file from a data grid view:
    Code:
    Dim StrExport As String = ""
                For Each C As DataGridViewColumn In DataGridView1.Columns
                    StrExport &= "" & C.HeaderText & ","
                Next
                StrExport = StrExport.Substring(0, StrExport.Length - 1)
                StrExport &= Environment.NewLine
    
    
                For Each R As DataGridViewRow In DataGridView1.Rows
    
                    For Each C As DataGridViewCell In R.Cells
                        If Not C.Value Is Nothing Then
                            StrExport &= "" & C.Value.ToString & ","
                        End If
                    Next
                    StrExport = StrExport.Substring(0, StrExport.Length - 1)
                    StrExport &= Environment.NewLine
                Next
    
                Dim tw As IO.TextWriter = New IO.StreamWriter(Application.StartupPath & "\file.csv")
                tw.Write(StrExport)
                tw.Close()
    It works but it adds an extra line in beginning of the file representing dgv headers ("Name", "Last Name", "Age", etc.)
    Which cause damage next time I call/open this file.

    How can I fix it? I added more negative numbers in for loop and increased starting point, but VS crashed... xd

  2. #2
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,669

    Re: Removing first row (headers) of a dgv to a csv file

    I'm guessing that you didn't bother to set some breakpoints and step through the code. If you had you would have seen that htese lines:
    Code:
                For Each C As DataGridViewColumn In DataGridView1.Columns
                    StrExport &= "" & C.HeaderText & ","
                Next
                StrExport = StrExport.Substring(0, StrExport.Length - 1)
                StrExport &= Environment.NewLine
    Are what create that header line, and that deleting them would have solved the problem.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  3. #3
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,262

    Re: Removing first row (headers) of a dgv to a csv file

    Well, it looks like your creating it yourself

    Code:
                For Each C As DataGridViewColumn In DataGridView1.Columns
                    StrExport &= "" & C.HeaderText & ","
                Next
                StrExport = StrExport.Substring(0, StrExport.Length - 1)
                StrExport &= Environment.NewLine
    Try commenting that out.

  4. #4
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,987

    Re: Removing first row (headers) of a dgv to a csv file

    Take a look at this function:
    Code:
    Private Function DataGridViewToCsv(grid As DataGridView, Optional ByVal includeHeaders As Boolean = False) As String
        Dim builder = New Text.StringBuilder()
    
        If (includeHeaders) Then
            builder.AppendLine(String.Join(",", grid.Columns.Cast(Of DataGridViewColumn).Select(Function(cell) cell.HeaderText).ToArray()))
        End If
    
        For Each row In grid.Rows.Cast(Of DataGridViewRow)
            If (row.IsNewRow) Then
                Continue For
            End If
            builder.AppendLine(String.Join(",", row.Cells.Cast(Of DataGridViewCell).Select(Function(cell) cell.Value?.ToString()).ToArray()))
        Next
    
        Return builder.ToString()
    End Function
    What it does is:
    1. Declare a new StringBuilder, which is generally more effective then concatenating strings on the fly
    2. Check if the output should contain the column headers
      1. if so, then append a line with the column header text, separated by a comma
    3. Loop over every row
    4. Check if the currently iterated row is a new row
      1. if so, then skip it
    5. Append a line with the cell data, separated by a comma


    To use the function, call:
    Code:
    Dim csv = DataGridViewToCsv(DataGridView1) ' csv without headers
    IO.File.WriteAllText(IO.Path.Combine(Application.StartupPath, "file.csv"), csv)
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  5. #5

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    381

    Re: Removing first row (headers) of a dgv to a csv file

    ♥_♥ Thanks to all, my shortest thread ever...

    I'm not really into visual studio people, sorry I act like a noob. I'm microcontroller pro. Bye for now

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width