0

I found this post about DataGridView to CSV File and I am wondering if someone knows how to export fields that are only Visible = True?

Private Sub ExportCSVButton_Click(sender As Object, e As EventArgs) Handles ExportCSVButton.Click
        Dim headers = (From header As DataGridViewColumn In PadGridView.Columns.Cast(Of DataGridViewColumn)()
                       Select header.HeaderText).ToArray
        Dim rows = From row As DataGridViewRow In PadGridView.Rows.Cast(Of DataGridViewRow)()
                   Where Not row.IsNewRow
                   Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
        Using sw As New IO.StreamWriter("export.csv")
            sw.WriteLine(String.Join(",", headers))
            For Each r In rows
                sw.WriteLine(String.Join(",", r))
            Next
        End Using
        Process.Start("export.csv")
End Sub
Jane Doe
  • 21
  • 6

1 Answers1

1

Get the visible columns in an array, then you can use that to filter the headers and the row cells:

   Dim visibleColumns = (From header As DataGridViewColumn In PadGridView.Columns.Cast(Of DataGridViewColumn)()
                   Where header.Visible
                  Select header.Index).ToArray

    Dim headers = (From header As DataGridViewColumn In PadGridView.Columns.Cast(Of DataGridViewColumn)()
                   Where visibleColumns.Contains(header.Index)
                  Select header.HeaderText).ToArray

    Dim rows = From row As DataGridViewRow In PadGridView.Rows.Cast(Of DataGridViewRow)()
               Where Not row.IsNewRow
           Select Array.ConvertAll((From x In row.Cells.Cast(Of DataGridViewCell).ToArray Where visibleColumns.Contains(x.ColumnIndex)).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))

    Using sw As New IO.StreamWriter("export.csv")
        sw.WriteLine(String.Join(",", headers))
        For Each r In rows
            sw.WriteLine(String.Join(",", r))
        Next
    End Using

    Process.Start("export.csv")
Chase Rocker
  • 1,908
  • 2
  • 13
  • 14