Skip to content

Exporting a datagridview to a csv file

Doug Ancil

Asked Jan 24, 2011, 7:06 AM EST1 answer
Share
LinkedInX

I am writing a form that will allow users to see the data from an executed stored procedure in a datagridview and then to export that same data as a csv file. I found this code:

VB.NET
 Imports System.Data.SqlClient

Public Class Payrollfinal
    Private Sub Payrollfinal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub
    Private Sub payrollsubmitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles payrollsubmitButton.Click
        Dim oCmd As System.Data.SqlClient.SqlCommand
        Dim oDr As System.Data.SqlClient.SqlDataReader
        oCmd = New System.Data.SqlClient.SqlCommand
        Dim _CMD As SqlCommand = New SqlCommand
        Dim adapter As System.Data.SqlClient.SqlDataAdapter
        Dim ds As New DataSet
        Try
            With oCmd
                .Connection = New System.Data.SqlClient.SqlConnection("Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx")
                .Connection.Open()
                .CommandType = CommandType.StoredProcedure
                .Parameters.AddWithValue("@payperiodstartdate", payperiodstartdate)
                .Parameters.AddWithValue("@payperiodenddate", payperiodenddate)
                .CommandText = "sp_allsum"
                oDr = .ExecuteReader()
                oCmd.Connection.Close()
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            oCmd.Connection.Close()
        End Try

        Try
            adapter.Fill(ds)

            If (ds Is Nothing) Then
                'it's empty
                MsgBox("There was no data for this time period, press Ok to continue", "No Data")
                oCmd.Connection.Close()
                Exceptions.Hide()
            Else
                'it exists and there are rows 
                adapter.Fill(ds)
                oCmd.Connection.Close()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            oCmd.Connection.Close()
        End Try
    End Sub
    Private Sub exportfileButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exportfileButton.Click
        'Declaration of Variables
        Dim dt As DataTable
        Dim dr As DataRow
        Dim myString As String
        Dim bFirstRecord As Boolean = True
        Dim myWriter As New System.IO.StreamWriter("C:\payroll.csv")
        myString = ""
        Try
            For Each dt In MyDataSet.Tables
                For Each dr As DataRow In dt.Rows
                    bFirstRecord = True
                    For Each field As Object In dr.ItemArray
                        If Not bFirstRecord Then
                            myString.AppendText(",")
                        End If
                        myString.AppendText(field.ToString)
                        bFirstRecord = False
                    Next
                    'New Line to differentiate next row
                    myString.AppendText(Environment.NewLine)
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        'Write the String to the Csv File
        myWriter.WriteLine(myString)
        'Clean up
        myWriter.Close()
    End Sub

and when two things happen when I try to use this code (which I modified after finding it on another site)
1. Intellisense tells me that MyDataSet is not defined.
2. When I define MyDataSet as
Dim MyDataSet as New Dataset
Intellisense tells me that I'm told that AppendText is not part of String. Can anyone assist?

Thank you,

Doug

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Suthish Nair
    0
    change your code..
    VB.NET
    Dim myString As StringBuilder
    Dim bFirstRecord As Boolean = True
    Dim myWriter As New System.IO.StreamWriter("C:\payroll.csv")
    myString.Append("")
    Try
      For Each dt In MyDataSet.Tables
        For Each dr As DataRow In dt.Rows
          bFirstRecord = True
          For Each field As Object In dr.ItemArray
            If Not bFirstRecord Then
              myString.Append(",")
            End If
            myString.Append(field.ToString)
            bFirstRecord = False
          Next
    VB.NET
         'New Line to differentiate next row
         myString.Append(Environment.NewLine)
        Next
       Next
    Catch ex As Exception
       MsgBox(ex.Message)
    End Try
    'Write the String to the Csv File
    myWriter.WriteLine(myString.ToString())
    0