Click here to Skip to main content
15,886,578 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 & ","
    Next
    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 & ","
                Else
                    StrExport &= "" & "" & ","
                End If
            Next
        Else
            StrExport = StrExport.Substring(0, StrExport.Length - 1)
            StrExport &= Environment.NewLine
        End If
    Next
    '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\Work.io\Work.io\bin\Debug\Session.csv", False)
    tw.Write(StrExport)
    tw.Close()
End Sub
Tags: Visual Basic, DataGridView, CSV

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



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 http://www.codeproject.com/info/cpol10.aspx.



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