Friday, August 13, 2010

Datagridview to text file

What are we cooking today?
A way to get what you have in a datagridview into a .txt file

Recipe

Public Shared Function DatagridviewToTextFile(ByVal strFileWithPath As String, ByVal dgv As DataGridView) As String
        Dim fsStream As New FileStream(strFileWithPath, FileMode.Create, FileAccess.Write)
        Dim swWriter As New StreamWriter(fsStream)
        Dim LineToWrite As String = String.Empty

        Try
            For rowIndex As Integer = 0 To dgv.Rows.Count - 1
                LineToWrite = String.Empty
                For colIndex As Integer = 0 To dgv.Columns.Count - 1
                    LineToWrite &= "," & dgv.Rows(rowIndex).Cells(colIndex).Value.ToString
                Next
                LineToWrite = LineToWrite.Remove(0, 1) 'remove the first comma
                swWriter.WriteLine(LineToWrite)
            Next
            swWriter.Flush()
            swWriter.Close()

            Return "File was saved succesfully!"
        Catch ex As Exception
            Throw New Exception(ex.Message)
            Return "Error writting to file -" & ex.Message
        End Try

    End Function





No comments:

Post a Comment