Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
The code below successfully writes the selected row of a DataGridView to a .csv.
However, everytime I select a row and write it to the file via a button click, it is also writing the column headers multiple times, therefore stuffing up the CSV file.

You can see the error it is creating in the CSV file here Error Image- DGV[^].

How can I do it so it doesn't write the headers at all, and skips them completely.
Thanks!

What I have tried:

Private Sub btnToSession_Click(sender As Object, e As EventArgs) Handles btnToSession.Click
    'PURPOSE: Write only selected DataGridView row to Session.csv
    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
    'Only the row which is selected will be written
    For Each R As DataGridViewRow In dataGVGeneral.Rows
        If R.Selected = True Then
            For Each C As DataGridViewCell In R.Cells
                If Not C.Value Is Nothing Then
                    StrExport &= "" & C.Value.ToString & ","
                Else
                    StrExport &= "" & "" & ","
                End If
            Next
        Else
            StrExport = StrExport.Substring(0, StrExport.Length - 1)
            StrExport &= Environment.NewLine
        End If
    Next
    'ROLE: Given ({filePath}, True)- Doesn't overwrite file, adds selected row to file under all other values.
    Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\Work.io\Work.io\bin\Debug\Session.csv", True)
    tw.Write(StrExport)
    tw.Close()
    'Delete Row from dataGVGeneral once saved to Session.csv
    deleteRow()
End Sub
Posted
Updated 4-Aug-20 1:02am

Yes, because that is what you are telling it to do!
You create your headers at the top of the method, and append the whole data to the file at the end.
If you look at the documentation (StreamWriter Constructor (System.IO) | Microsoft Docs[^]) then you will see that this code:
VB
Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\Work.io\Work.io\bin\Debug\Session.csv", True)
Specifically opens the file stream to append data, so the original data isn't overwritten.
If that isn't what you want to do, then change the True to a False to throw away the existing file content first, or change your code at the start of the method to detect if you need to add headers. That may be as simple as "does the file exist?" or you may have to be cleverer than that and check the file content to see if there is a header line (or indeed any data at all).

How many times do I have to tell you to stop guessing and start thinking? :laugh:
 
Share this answer
 
Comments
Shaheer Rizwan 4-Aug-20 5:25am    
Ive tried changing it to False, when I changed it to false, every time I added a new selected row to the file, it'll completely rewrite the file and the original rows I seleted would not be there. Therefore, I set it to true, which doesn't overwrite the file, but now its writing the headers as well.
Garth J Lancaster 4-Aug-20 5:32am    
I think you need to check OriginalGriff's reply carefully - especially "That may be as simple as "does the file exist?" or you may have to be cleverer than that and check the file content to see if there is a header line (or indeed any data at all)." - you've been tweaking true to false and back again now - so it's obvious that on it's own is not going to work - hence why I would have written a temporary file and merged it - that way extra header lines could be removed, if you didnt implement smarter logic as suggested
OriginalGriff 4-Aug-20 5:52am    
"stop guessing and start thinking"

Sound familiar yet? :laugh:
Shaheer Rizwan 4-Aug-20 5:53am    
yea ive been trying for ages. I thought id get some help as im struggling.
OriginalGriff 4-Aug-20 6:41am    
You are struggling *because* you are guessing instead of thinking.

It's pretty obvious that if you write headers into a file multiple times you will get "multiple headers" and the only way to prevent that is ... write them once. If you think about what you are doing and what you are trying to do, it's obvious anyway. If you wrote the numbers down on a sheet of paper, you wouldn't add headers unless the sheet was blank, would you? So why not think about it and expand that logic to your application?

I'm not trying to be nasty here - but unless you do start thinking about what you are doing you really aren't going to get far on your own - as you have seen over the last week or so!

Guessing doesn't work: in software, or in the real world. Thinking and learning does!
I have explained what you need to do (more than once), and offered some sample code to do this correctly. But you continue to ignore it and repeat the same question. Unless you start taking the advice you have been given you are just wasting your time, let alone everyone's here.
 
Share this answer
 
Comments
Shaheer Rizwan 4-Aug-20 7:05am    
yea it was the code you put. Idk why but it messed up, I tried a bit of modification and it finally worked

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