hi all,

i made a proejct that runs sql command to datagridview and than export it to csv file, everything going fine but i got line break problem. Here my export code;

im filePath As String = "C:\FULLWork\csv\dbslimit.csv"
        Dim delimiter As String = ";"
        Dim sb As New StringBuilder()

        For i As Integer = 0 To DataGridView1.Rows.Count - 1
            Dim array As String() = New String(DataGridView1.Columns.Count - 1) {}

            If i.Equals(0) Then

                For j As Integer = 0 To DataGridView1.Columns.Count - 1
                    array(j) = DataGridView1.Columns(j).HeaderText
                Next
                sb.AppendLine([String].Join(delimiter, array))
            End If

            For j As Integer = 0 To DataGridView1.Columns.Count - 1
                If Not DataGridView1.Rows(i).IsNewRow Then
                    array(j) = DataGridView1(j, i).Value.ToString()
                End If
            Next
            If Not DataGridView1.Rows(i).IsNewRow Then
                sb.AppendLine([String].Join(delimiter, array))
            End If
        Next
        File.WriteAllText(filePath, sb.ToString(), System.Text.Encoding.Default)

the problem begins 474. line
test2

The problem comes from Carriage-Returns inside the cells of the DataGridView, right?
If you chek the content of each cell (or target cells) for unwanted chars, you can replace them before writing them to the CSV.

Like:
...Value.ToString().Replace(Char(13), " ").Replace(Char(10), " ").Replace(Char(9), " ")

There are other ways, also.

commented: agree +8

ToString().Replace(Char(13), " ").Replace(Char(10), " ").Replace(Char(9), " ")

it works thanks

but still some lines with it, is there any other characters expect Char(13), " ").Replace(Char(10), " ").Replace(Char(9), " ") ?

Please change the Char to Chr (my fault).

Also, you might want to try something a little more heavy-duty like a Regex.Replace where you take out anything that is not desired.

Imports System.Text.RegularExpressions
Module Module1
   Sub Main()
      Dim rxPrintable As New Regex("[^0-9A-Za-z _]") 'eliminate anything not in this list'
      Dim strData As String = "this*is*neat" & Chr(9) & "and[so]is" & Chr(13) & "this)"
      Console.WriteLine(rxPrintable.Replace(strData, " "))
   End Sub
End Module
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.