Writing Data from a DataGridView to a Text File

Benemin

Member
Joined
Feb 17, 2010
Messages
12
Location
England
Programming Experience
Beginner
I have been using this code, see below, to try and write data from the DataGridView to a text file. It works but it puts an extra comma after each line and thinks that there has been another line so puts an extra 4 commas on a new line. So the text file looks like this:

VB.NET:
9,Here to There,1,15,
8,Hell to Heaven,16,34,
,,,,

I'm looking for any help for a way to get rid of the extra commas or an entirely different way of doing this whole process.

If you need any extra information - please do ask. :D

VB.NET:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Dim fsStream As New FileStream("routes.txt", FileMode.Create, FileAccess.Write)
        Dim swWriter As New StreamWriter(fsStream)

        Try
            Dim temp As Integer
            For temp = 0 To dg.Columns.Count - 1
                Dim temp2 As Integer
                For temp2 = 0 To dg.Columns.Count - 1
                    swWriter.Write(dg.Rows.Item(temp).Cells.Item(temp2).Value)
                    swWriter.Write(",")
                Next
                swWriter.WriteLine("")
            Next
            swWriter.Flush()
            MsgBox("Data Saved Successfully")
            swWriter.Close()
        Catch ex As Exception
        End Try

    End Sub
 
VB.NET:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Dim fsStream As New FileStream("routes.txt", FileMode.Create, FileAccess.Write)
        Dim swWriter As New StreamWriter(fsStream)
        Dim LineToWrite as String = String.Empty

        Try
            For _Row as Integer = 0 To dg.Rows.Count - 1
                LineToWrite = String.Empty
                For _Column as Integer = 0 To dg.Columns.Count - 1
                    LineToWrite &= "," & dg.Rows(_Row).Cells(_Column).Value.ToString
                Next
                LineToWrite = LineToWrite.Remove(0,1) 'remove the first comma
                swWriter.WriteLine(LineToWrite)
            Next
            swWriter.Flush()
            swWriter.Close()
            Messagebox.Show("Data Saved Successfully")
        Catch ex As Exception
        End Try

    End Sub
 
Thanks - it looks as though it should work, but I get the following error when I try and save the data:

VB.NET:
A first chance exception of type 'System.NullReferenceException' occurred in Program.exe

Any idea why it isn't working?
 
What does the stack trace say? What line does the error occur on? What is your Datagridview called?
 
I have no idea what a stack trace is - could you tell me how to display it in the environment?
It doesn't give a specific line where the error occurs.
And the DataGridView is called dg
 
Last edited:
I have no idea what a stack trace is - could you tell me how to display it in the environment?

A good starting point would be Debug - Windows - Immediate :)

It doesn't give a specific line where the error occurs.

Have you tried stepping through it? Debug - Step Into?
 
In the immediate window it says:

VB.NET:
A first chance exception of type 'System.NullReferenceException' occurred in Bus Management and Fare System.exe

when I press the save button.

And when I tried the Step Into thing - it went through the code and performed it all but no error came up and the data hadn't been writen to the text file.
 
Well, you can either:-

1. Comment out the Try..Catch..End Try so that it actually fails at the correct error. This will show you exactly where the error is.

2. Think "what could be Null that is causing the NullReferenceException?" My guess is that you have a row at the bottom of your Datagridview that contains no data, which is why you were ending up with the row of commas in your original version. Try this:-

VB.NET:
        Try
            For _Row as Integer = 0 To dg.Rows.Count - 1
                LineToWrite = String.Empty
                For _Column as Integer = 0 To dg.Columns.Count - 1
                    If dg.Rows(_Row).Cells(_Column).Value IsNot Nothing then 
                        LineToWrite &= "," & dg.Rows(_Row).Cells(_Column).Value.ToString
                    Else
                        LineToWrite &= ","
                    End If
                Next
                LineToWrite = LineToWrite.Remove(0,1) 'remove the first comma
                swWriter.WriteLine(LineToWrite)
            Next
            swWriter.Flush()
            swWriter.Close()
            Messagebox.Show("Data Saved Successfully")
        Catch ex As Exception
            Messagebox.Show("An error occurred")
        End Try
 
VB.NET:
Dim writer As New IO.StreamWriter("routes.txt")
For Each row As DataGridViewRow In Me.DataGridView1.Rows
    If Not row.IsNewRow Then
        Dim values As New List(Of String)
        For Each cell As DataGridViewCell In row.Cells
            values.Add(CStr(cell.Value))
        Next
        writer.WriteLine(String.Join(",", values.ToArray))
    End If
Next
writer.Close()
 

Latest posts

Back
Top