简体   繁体   中英

Writing multiple selected DataGridView rows to CSV

The code below successfully allows for me to write a selected row to a.csv file.

I'm having problems where, when I select multiple rows and try and write it to the file, it puts all of the row on the same line of the.csv file.

How can I modify the code below so that it allows for multiple rows to be selected, and it writes each row to a new line of the.csv file?

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
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()

On the line StrExport = StrExport.Substring(0, StrExport.Length - 1) , I think you meant to use &= instead of = .

However, you should be using a StringBuilder to create the string because it is more efficient when concatenating more than about ten pieces of string together.

To join strings together with a comma/anything else between,String.Join is useful because you don't have to worry about the final comma.

And finally, with a little bit of LINQ you can make the code quite a bit shorter but still fairly easy to understand:

Private Sub bnSaveSelected_Click(sender As Object, e As EventArgs) Handles bnSaveSelected.Click
    Dim sb As New Text.StringBuilder()
    sb.AppendLine(String.Join(",", dataGVGeneral.Columns.Cast(Of DataGridViewColumn).Select(Function(c) c.HeaderText)))

    For Each dr As DataGridViewRow In dataGVGeneral.Rows
        If dr.Selected Then
            sb.AppendLine(String.Join(",", dr.Cells.Cast(Of DataGridViewCell).Select(Function(c) c.Value.ToString())))
        End If
    Next

    IO.File.WriteAllText("C:\temp\SampleCsv.csv", sb.ToString())

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM