Home > Net >  How to export csv from datagridview only visible column in VB.Net?
How to export csv from datagridview only visible column in VB.Net?

Time:06-23

I'm working on scraping program, the next step from my program after scraping item is generate/export from datagridview into csv file. I have made the save code like below, but i just want to export only a visible column. How can i do like that?

Private Sub CmdCSV_Click(sender As Object, e As EventArgs) Handles CmdCSV.Click
        Dim sfd As New SaveFileDialog()
        sfd.FileName = "export-csv"
        sfd.Filter = "CSV File | *.csv"

        If sfd.ShowDialog() = DialogResult.OK Then
            Using sw As StreamWriter = File.CreateText(sfd.FileName)
                Dim dgvColumnNames As List(Of String) = DataGridView1.Columns.Cast(Of DataGridViewColumn).ToList().Select(Function(c) c.Name).ToList()

                sw.WriteLine(String.Join(";", dgvColumnNames))

                For Each row As DataGridViewRow In DataGridView1.Rows
                    Dim rowData As New List(Of String)

                    For Each column As DataGridViewColumn In DataGridView1.Columns
                        rowData.Add(Convert.ToString(row.Cells(column.Name).Value))
                    Next
                    sw.WriteLine(String.Join(";", rowData))
                Next

            End Using
        End If
    End Sub

CodePudding user response:

Firstly, there's no point calling ToList twice here:

Dim dgvColumnNames As List(Of String) = DataGridView1.Columns.Cast(Of DataGridViewColumn).ToList().Select(Function(c) c.Name).ToList()

You don't need a generic List to do the Select, so drop the first ToList:

Dim dgvColumnNames = DataGridView1.Columns.
                                   Cast(Of DataGridViewColumn).
                                   Select(Function(c) c.Name).
                                   ToList()

If you want to filter that list to include only visible columns, that's what you do. The Where method is how you filter:

Dim dgvColumnNames = DataGridView1.Columns.
                                   Cast(Of DataGridViewColumn).
                                   Where(Function(c) c.Visible).
                                   Select(Function(c) c.Name).
                                   ToList()

You should also replace this:

Dim rowData As New List(Of String)

For Each column As DataGridViewColumn In DataGridView1.Columns
    rowData.Add(Convert.ToString(row.Cells(column.Name).Value))
Next

with this:

Dim rowData As New List(Of String)

For Each columnName In dgvColumnNames
    rowData.Add(Convert.ToString(row.Cells(columnName).Value))
Next

or, more simply, this:

Dim rowData = dgvColumnNames.Select(Function(s) row.Cells(columnName).Value.ToString()).ToList()

That last ToList isn't required either, because String.Join accepts an IEnumerable(Of String). Don't take the extra time and effort to convert things to a generic List unless you actually need one.

  • Related