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