Click here to Skip to main content
15,868,164 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I've managed to code my DataGridView to load the CSV file. I now want it so when new records are added and updated, for the CSV to be updated when a button is clicked.

UPDATE: The code below is working in terms of saving the newly entered data. However, as im loading the file into the dataGridView, it is duplicating the data which was already in it, and therefore messing up.

How can I improve the code below so that it overwrites the CSV file.

What I have tried:

Private Sub btnSaveGeneralDGV_Click(sender As Object, e As EventArgs) Handles btnSaveGeneralDGV.Click
        Dim StrExport As String = ""
        For Each C As DataGridViewColumn In dataGVGeneral.Columns
            StrExport &= """" & C.HeaderText & ""","
        Next
        StrExport = StrExport.Substring(0, StrExport.Length - 1)
        StrExport &= Environment.NewLine

        For Each R As DataGridViewRow In dataGVGeneral.Rows
            For Each C As DataGridViewCell In R.Cells
                If Not C.Value Is Nothing Then
                    StrExport &= """" & C.Value.ToString & ""","
                Else
                    StrExport &= """" & "" & ""","
                End If
            Next
            StrExport = StrExport.Substring(0, StrExport.Length - 1)
            StrExport &= Environment.NewLine
        Next

        Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\Work.io\Work.io\bin\Debug\ListofTasks.csv", True)
        tw.Write(StrExport)
        tw.Close()
Posted
Updated 27-Jul-20 17:37pm
v2

1 solution

Not sure what your problem is

1) Add a new button for 'saving updates'
2) Add an event handler for the button click from (1)
3) Open a file for output - I suggest you write a a temporary file eg E:\SAT\Work.io\Work.io\bin\Debug\ListofTasks.csv.tmp" inside a using block
4) loop for each Row of dataGVGeneral
5) concantenate the columns of the row using join & ',' to get a CSV
6) write the line to the file
7) (outside the using & loop) archive the original file and rename the updated file without the '.tmp' on the end

You could change 7 to merge the files or such as you need

FWIW I think you could still do better using a datatable and the csvhelper library eg CsvHelper[^]

[Edit 2] This may be useful if you go the datatable route Writing a DataTable to a CSV File[^]
 
Share this answer
 
v3
Comments
Shaheer Rizwan 27-Jul-20 22:03pm    
Is there a way to clear the CSV file and rewrite its contents based on the DataGridView.

Can I use something like this and then simply add the clear CSV line?

Private Sub btnExportData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportData.Click
Dim StrExport As String = ""
For Each C As DataGridViewColumn In DataGridView1.Columns
StrExport &= """" & C.HeaderText & ""","
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine

For Each R As DataGridViewRow In DataGridView1.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= """" & C.Value.ToString & ""","
Else
StrExport &= """" & "" & ""","
End If
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
Next

Dim tw As IO.TextWriter = New IO.StreamWriter("C:\Test1.CSV")
tw.Write(StrExport)
tw.Close()
End Sub <code>
Garth J Lancaster 27-Jul-20 22:53pm    
of course you CAN overwrite a file - eg, looking at your code
Dim tw As IO.TextWriter = New IO.StreamWriter("C:\Test1.CSV")
if you did this
Dim tw As IO.TextWriter = New IO.StreamWriter("C:\Test1.CSV", True )
it would overwrite the file .. the issue is about 'safety' in my mind ..
Shaheer Rizwan 27-Jul-20 23:33pm    
Hey mate, I just tried this again, and its not overwriting the whole file and is duplicating the records already present after loading it. Is there another way. Sorry to bother you im just a bit stuck
Shaheer Rizwan 27-Jul-20 23:37pm    
Check above for the exact code
Garth J Lancaster 28-Jul-20 6:41am    
sorry, take off the , True or change it to , False - I misread the Microsoft documentation - https://docs.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=netcore-3.1#System_IO_StreamWriter__ctor_System_String_System_Boolean_

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