Welcome to MSDN Blogs Sign in | Join | Help

Printing DataGridView contents in CSV format

  

While answering questions on the windowsforms.net regarding datagridview, i noticed that a good number of people wanted to store the contents of the datagridview in a csv (comma separated value format).

 

In this blog, i am just writing a simple solution for this.  We do this by printing each row of the Datagridview.

 

The following block of code in VB accomplishes this task. DataGridView1 has to be stored in the csv format.

 

        Dim numCols As Integer = DataGridView1.ColumnCount

        Dim numRows As Integer = DataGridView1.RowCount - 1

        Dim strDestinationFile As String = "c:\\output.txt"

 

        Using tw As TextWriter = New StreamWriter(strDestinationFile)

 

            'writing the header

            For indexCols As Integer = 0 To numCols - 1

                tw.Write(DataGridView1.Columns(indexCols).HeaderText)

                If (indexCols <> numCols - 1) Then

                    tw.Write(", ")

                End If

            Next

            tw.WriteLine()

 

            'writing the data

            For indexRows As Integer = 0 To numRows - 1

                'print all column values for a row

                For indexCols As Integer = 0 To numCols - 1

                    tw.Write(DataGridView1.Rows(indexRows).Cells(indexCols).Value)

                    If (indexCols <> numCols) Then

                        tw.Write(", ")

                    End If

                Next

                tw.WriteLine()

            Next

 

        End Using

 

Also, in the above code you can notice usage of Using block.  Not only does Using intialize the resource but also disposes it.  If I were not making use of Using block, here,  I can also accomplish this by a try catch finally block as follows.  

        Dim tw As TextWriter

        Try

            tw = New StreamWriter(strDestinationFile)

            --------

            -------

        Catch ex As Exception

 

        Finally

            tw.Close()

        End Try

 

We can see that making use of Using block makes the code look less cumbersome and this is a very good feature in .Net

 

 

Published Friday, December 01, 2006 3:25 AM by nagasr

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

Wednesday, June 20, 2007 4:02 PM by Justin

# re: Printing DataGridView contents in CSV format

Thank You,  this was copy paste and worked great.

Sunday, March 02, 2008 7:42 PM by audi

# re: Printing DataGridView contents in CSV format

This simplistic solution doesn't work in cases where a datagridview cell value contains embedded commas -- for example: June 12, 1958 will be written as June 12, 1958, and the value will appear in two columns!

Audi

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker