Hi

I am trying to export the contents of a datagridview to a text file but I only want to see the data that is visible. I have hidden certain non important columns which I do not want to export.
Please could someone help me modify the code accordingly.

Private Sub buttonSave_Click(sender As Object, e As EventArgs)
    Dim filePath As String = Me.TextBox1.Text
    Dim delimiter As String = ";"
    Dim sb As New StringBuilder()
    'create columnNames:
    For i As Integer = 0 To dataGridView1.Rows.Count - 1
        Dim array As String() = New String(dataGridView1.Columns.Count - 1) {}
        If i.Equals(0) Then
            'get column header text from all columns:
            For j As Integer = 0 To dataGridView1.Columns.Count - 1
                array(j) = dataGridView1.Columns(j).HeaderText
            Next
            sb.AppendLine([String].Join(delimiter, array))
        End If
        'get values from columns for specific row (row[i]):
        For j As Integer = 0 To dataGridView1.Columns.Count - 1
            If Not dataGridView1.Rows(i).IsNewRow Then
                array(j) = dataGridView1(j, i).Value.ToString()
            End If
        Next
        If Not dataGridView1.Rows(i).IsNewRow Then
            sb.AppendLine([String].Join(delimiter, array))
        End If
    Next
    File.WriteAllText(filePath, sb.ToString())
End Sub

Here's one way using LINQ:

Private Sub buttonSave_Click(sender As Object, e As EventArgs)
    Dim filePath As String = Me.TextBox1.Text
    Dim delimiter As String = ";"
    Dim sb As New StringBuilder()
    'create columnNames:
    sb.AppendLine(Join((From c As DataGridViewColumn In DataGridView1.Columns
                        Where c.Visible = True
                        Select c.HeaderText).ToArray, delimiter))
    'get values from visible columns
    For Each r As DataGridViewRow In DataGridView1.Rows
        If Not r.IsNewRow Then
            sb.AppendLine(Join((From c As DataGridViewCell In r.Cells
                                Where DataGridView1.Columns(c.ColumnIndex).Visible = True
                                Select c.FormattedValue).ToArray, delimiter))
        End If

    Next
    File.WriteAllText(filePath, sb.ToString())
End Sub

Basically this uses the ColumnIndex property of the indiviual cell to identify the column and check if it is visible.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.