Results 1 to 7 of 7

Thread: Saving DataGridView to csv? | SOLVED

Threaded View

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Nov 2016
    Posts
    95

    Saving DataGridView to csv? | SOLVED

    Hello! I am following a tutorial on how to save a DataGridView to csv and it won't save. I followed the tutorial correctly, something I did wrong?
    Code:
    Public Class frmMain
        Private Sub btnSubmitData_Click(sender As Object, e As EventArgs) Handles btnSubmitData.Click
            DataGridView1.Rows.Add(txtName.Text, txtCredit.Text, txtPrize.Text, txtPurchaser.Text, 3)
        End Sub
    
        Private Sub btnSaveData_Click(sender As Object, e As EventArgs) Handles btnSaveData.Click
            'Create Empty String
            Dim thecsvfile As String = String.Empty
            'get column headers
            For Each column As DataGridViewColumn In DataGridView1.Columns
                thecsvfile = thecsvfile & column.HeaderText & ","
            Next
            'trim the last comma
            thecsvfile = thecsvfile.TrimEnd(",")
            'add the line to the output
            thecsvfile = thecsvfile & vbCr & vbLf
            'get the rows
            For Each row As DataGridViewRow In DataGridView1.Rows
                'get the cells
                For Each cell As DataGridViewCell In row.Cells
                    thecsvfile = thecsvfile & cell.FormattedValue & ","
                Next
                'trim the last comma
                thecsvfile = thecsvfile & vbCr & vbLf
            Next
            'write file
            My.Computer.FileSystem.WriteAllText("export.csv", thecsvfile, False)
        End Sub
    End Class
    Shouldn't the data save automatically to the debug? Plan to do a save dialog after main functionality works.

    SOLUTION:
    Code:
            SaveFileDialog1.Filter = "CSV File (*.csv*)|*.csv"
            SaveFileDialog1.ShowDialog()
            My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName, thecsvfile, False)
    Last edited by Dragnorian; May 23rd, 2017 at 01:16 AM. Reason: Solution Found

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