Question Exporting DataGridView to CSV

BleepyEvans

Active member
Joined
May 2, 2011
Messages
41
Programming Experience
1-3
Hi,

Im wondering how I can save the contents of a datagrid view do I can close the application, reopen and the contents still be there.
I have multiple DataGridViews so I need to beable to save more than one.

Thanks.
 
Last edited:
That depends on what the contents are, if it is a DataTable you can just call the WriteXml method and specify the filename, eg dt.WriteXml("filename"), and same for reading using ReadXml method. If not perhaps it could be a good idea to start using a DataTable now.
 
I found this, but I get "Access to path ... is denied" when I try save to my desktop using specialfolders.

VB.NET:
Dim sr As StreamWriter = File.CreateText(strExportFileName)
        Dim strDelimiter As String = strDelimiterType
        Dim intColumnCount As Integer = DataGridView.Columns.Count - 1
        Dim strRowData As String = ""

        If blnWriteColumnHeaderNames Then
            For intX As Integer = 0 To intColumnCount
                strRowData += Replace(DataGridView.Columns(intX).Name, strDelimiter, "") & _
                IIf(intX < intColumnCount, strDelimiter, "")
            Next intX
            sr.WriteLine(strRowData)
        End If

        For intX As Integer = 0 To DataGridView.Rows.Count - 1

            strRowData = ""

            For intRowData As Integer = 0 To intColumnCount
                strRowData += Replace(DataGridView.Rows(intX).Cells(intRowData).Value, strDelimiter, "") & _
                    IIf(intRowData < intColumnCount, strDelimiter, "")
            Next intRowData

            sr.WriteLine(strRowData)

        Next intX
        sr.Close()
        MsgBox("saved!")
VB.NET:
Call subExportDGVToCSV(My.Computer.FileSystem.SpecialDirectories.Desktop, Me.driversGrid, False, ",")
 
Desktop is a folder, you have to add your file name to that. Use IO.Path.Combine method to combine the folder path with file name.
 
Loop through the Columns collection and write out each columns HeaderText.
 
Back
Top