Click here to Skip to main content
15,498,859 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm reading a CSV file into a DataGridView and having entered some data, I'd like to save back as CSV.

Someone suggested this code but it throws an error at the line


The new data is String.

Private Sub SaveGridDataInFile(ByRef fName As String)
        Using fSave As New SaveFileDialog
            fSave.FileName = fName
            If fSave.ShowDialog = Windows.Forms.DialogResult.OK Then
                fName = fSave.FileName

                Exit Sub
            End If
        End Using

            Dim lines As New List(Of String)
            For Each row As DataGridViewRow In DataGridView1.Rows
                Dim cells As New List(Of String)
                For cellNumber As Integer = 0 To (DataGridView1.Columns.Count - 1)
                    If Not TypeOf row.Cells.Item(cellNumber).Value Is DBNull Then




                    End If

                lines.Add(String.Join(","c, cells.ToArray))
            Dim csvString As String = String.Join(Environment.NewLine, lines.ToArray)
            IO.File.WriteAllText(fName, csvString)

        Catch e As Exception

            MessageBox.Show("Error occured while writing to the file." + e.ToString())

        End Try

    End Sub

I'd be very grateful if anyone could see why this was failing.

Updated 28-Feb-15 17:37pm
Mike Hankey 28-Feb-15 22:29pm    
What is the error message you are getting?
[no name] 1-Mar-15 9:15am     CRLF
Hi Mike, "Error occurred while writing to the file.System.NullRefereceException: Object reference not set to an instance of an object. Line 111" This is the line singled out above. Thanks DAvid
Richard MacCutchan 1-Mar-15 3:56am    
Step through the code with your debugger to see what the issue is.
Mike Hankey 1-Mar-15 9:24am    
The error you've indicated and the line that it's supposedly thrown on doesn't make any sense. As Richard says step through the code and you will likely find your problem.
[no name] 1-Mar-15 9:42am     CRLF
Got it! It was the ".ToString" in the line that was reporting the error. Removed it and now works fine. Thanks for your advice! David

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900