Click here to Skip to main content
14,641,302 members

Issue when writing multiple selected datagridview row to CSV

Shaheer Rizwan asked:

Open original thread
Im having a problem where, if I select multiple DataGridView rows, all the information is placed into one line of the .csv file, this is giving me issues when trying to load the file back up.

Instead of having to select and saving each row individually (They are selected so they write to another file), how can I change the code below, so that for each selected row, each row is written onto another line.

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 & ","
    StrExport = StrExport.Substring(0, StrExport.Length - 1)
    StrExport &= Environment.NewLine
    'Only the row which is selected will be writen
    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 & ","
                    StrExport &= "" & "" & ","
                End If
            StrExport = StrExport.Substring(0, StrExport.Length - 1)
            StrExport &= Environment.NewLine
        End If
    'ROLE: Given ({filePath}, False)- allows for the file to be completely overwritten with new data.
    Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\\\bin\Debug\Session.csv", False)
End Sub
Tags: VB.NET, DataGridView, CSV


When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100