vb.net Code:
'' We use some sequence of non-printing characters to replace the line breaks.
'' You can change these if any of these characters can be part of your regular text.
Const MyCrlfMark As String = ChrW(164) & ChrW(165) & ChrW(166)
'' This function converts our text to CSV compliant text
Function StringToCsvFormat(ByVal ParamArray fields() As String) As String
Dim output As String = ""
For Each field In fields
If String.IsNullOrEmpty(field) Then
field = ""
ElseIf field.Contains("""") Then
field = """" & field.Replace("""", """""") & """"
ElseIf field.Contains(",") Then
field = """" & field & """"
End If
field = field.Replace(vbCrLf, MyCrlfMark).Replace(vbCr, MyCrlfMark).Replace(vbLf, MyCrlfMark)
output &= field.Trim & ","
Next
' -- output &= vbCrLf
Return output
End Function
'' This function puts back the line breaks after we get our saved data back from disk.
Function CsvToStringFormat(ByVal field As String) As String
Return field.Replace(MyCrlfMark, vbCrLf)
End Function
vb.net Code:
Dim Rows = (From row In DataGridView1.Rows _
Where Not DirectCast(row, DataGridViewRow).IsNewRow _
Let RowItem = StringToCsvFormat(Array _
.ConvertAll( _
DirectCast(row, DataGridViewRow).Cells.Cast(Of DataGridViewCell).ToArray, _
Function(c As DataGridViewCell) _
If(c.Value Is Nothing, "", c.Value.ToString))) _
Select RowItem).ToArray
IO.File.WriteAllLines(tbDGVName.Text, Rows)
vb.net Code:
While Not MyReader.EndOfData
Try
Line = MyReader.ReadFields()
'' restore the line breaks
For i = 0 To line.Length - 1
Line(i) = CsvToStringFormat(Line(i))
Next
' For every column per line
' there must be a column in the DataGridView
sender.Rows.Add(New Object() {Line(0), Line(1), Line(2), Line(3), Line(4), Line(5), Line(6), Line(7), Line(8), Line(9), Line(10), CBool(Line(11)), Line(12), Line(13), Line(14), Line(15)})
sender.EndEdit()
' Line(4), Line(5), Line(6), Line(7), Line(8), Line(9), Line(10), Line(11), Line(12), Line(13), Line(14), Line(15), Line(16)})
Catch ex As FileIO.MalformedLineException
Errors.Add(ex.Message)
Catch ex As Exception
Errors.Add(ex.Message)
End Try
End While