Results 1 to 10 of 10

Thread: [RESOLVED] DGV Text File

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Resolved [RESOLVED] DGV Text File

    Hi

    I have my datagridview being loaded from a Text File and then being saved to a text file as a comma separated file - the commas obviously separate the columns.

    However in some of the cells prior to saving, I have data that i have inputted over two lines by pressing shift + return.. eg

    "SOLD
    10/05/2012"

    This saves fine, but obviously shows up in the text file as a line break, which then causes some issues when i choose to re open the info back into DGV.

    I'm wondering if anyone can help as to how i can code so that it saves as a line break within a cell, rather than a completely new line.

    Thanks

  2. #2
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: DGV Text File

    You could replace all the linebreaks with commas. Could you post a sample of your text file with these linebreaks ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV Text File

    Hi Niya

    Here's what one of the lines looks like...

    ,VOLVO,,,,,,SOLD
    10 05 2012,2:48,True,False,True,False,False,False,True
    So at the moment, the info is entered into the dgv by the user, they hit save, and this is how it saves. The cell with the line break is "SOLD 10 05 2012". When the text file is loaded back into the DGV it should appear in one cell, with a line break, however at the moment it throws an exception etc etc etc

  4. #4
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: DGV Text File

    Ok, does your text file have multiple rows ? If so, how do you separate them. My reason for asking is related to my earlier suggestion. If you replace all the linebreaks with commas you may end up combining several rows into a single row which would royally screw up the whole thing. We may need a way to distinguish different rows.

    A better solution would be to remove line breaks before saving to the text file. Perhaps you could replace them with some special character and when you load them back into the DataGridView, you convert them back into line breaks for display purposes.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV Text File

    Apologies Niya! That makes sense.

    So in the text file, new rows in the DGV are separated by a line break.

    Your solution to remove line breaks, replacing with a character and reading the character for display sounds great...can you advise on how to do that?

  6. #6
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: DGV Text File

    Here is an example:-
    vbnet Code:
    1. '
    2.         Dim st As String = "Hello" + Environment.NewLine + "World"
    3.  
    4.         MsgBox(st)
    5.  
    6.         'Replace line break with <br>
    7.         st = Replace(st, Environment.NewLine, "<br>")
    8.  
    9.         MsgBox(st)
    10.  
    11.  
    12.         'Replace <br> with real line break
    13.         st = Replace(st, "<br>", Environment.NewLine)
    14.  
    15.         MsgBox(st)
    I suggested using a special character but you could use anything you want. In the above example, I used a certain character sequence. IE <br>
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  7. #7
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: DGV Text File

    When I was in a situation similar to you, I had written this function for myself.
    Hope this would help you.

    vb.net Code:
    1. Function StringToCsvFormat(ParamArray fields() As String) As String
    2.     Dim output As String = ""
    3.     For Each field In fields
    4.         If String.IsNullOrEmpty(field) Then
    5.             field = ""
    6.         ElseIf field.Contains("""") Then
    7.             field = """" & field.Replace("""", """""") & """"
    8.         ElseIf field.Contains(",") Then
    9.             field = """" & field & """"
    10.         End If
    11.         field = field.Replace(vbCrLf, "; ").Replace(vbCr, "; ").Replace(vbLf, "; ")
    12.         output &= field.Trim & ","
    13.     Next
    14.     output &= vbCrLf
    15.     Return output
    16. End Function

    This writes one complete row at a time with a line break at the end.
    If you will be writing in parts and would like to put the line breaks yourself, then simply comment out the following line:
    output &= vbCrLf


    Sample Usage:
    Code:
    MyWriter.Write(StringToCsvFormat("value1", "val,ue2", "val""ue3", "val" & vbCr & "ue4"))
    This will write the values 1 to 4 preserving its commas etc. and will be correctly reloaded when read from any CSV complaint reader (or code) like Excel etc.

    The output will be:
    Code:
    value1    val,ue2    val"ue3    val; ue4
    Last edited by Pradeep1210; May 10th, 2012 at 02:33 PM.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV Text File

    Hi! Thanks for the replies and sorry for my delay.

    Just wondering where I should put either of the codes provided in my "save DGV" code so that line breaks in individual cells are identified, replaced and saved,

    and where I should put the code in my "Load" code so that the replaced cell line breaks are identified and swapped for ACTUAL line breaks in the cells?

    I've attached an example cell.

    And here are the relevant codes:

    SAVE CODE:

    Code:
    Dim Rows = (From row In DataGridView1.Rows _
                                    Where Not DirectCast(row, DataGridViewRow).IsNewRow _
                                    Let RowItem = String.Join(",", 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)
    
            If Dir(tbDGVName.Text) <> "" Then
                MsgBox("Saved")
            Else
                MsgBox("Grid not created")
            End If

    LOAD CODE:

    Code:
    Imports Microsoft.VisualBasic.FileIO
    Module Module1
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Function LoadTextFile( _
          ByVal sender As DataGridView, _
          ByVal FileName As String, _
          ByRef Errors As List(Of String)) As Boolean
    
            If Not IO.File.Exists(FileName) Then
                Errors.Add("Failed to locate '" & FileName & "'")
                Return False
            End If
    
            If sender.ColumnCount <> 16 Then
    
                Errors.Add("Must have three columns to load your text file., there are " & _
                           sender.ColumnCount.ToString & " columns presently.")
    
                Return False
    
            End If
    
            Using MyReader As New TextFieldParser(FileName)
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.Delimiters = New String() {","}
                Dim Line As String()
    
                sender.SuspendLayout()
    
                Try
                    While Not MyReader.EndOfData
                        Try
                            Line = MyReader.ReadFields()
                            '
                            ' 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
                            '
                            ' Report problem
                            '
                            Errors.Add(ex.Message)
                        Catch ex As Exception
                            Errors.Add(ex.Message)
                        End Try
                    End While
                Finally
                    sender.ResumeLayout()
                End Try
            End Using
    
            Return Errors.Count = 0
    
        End Function
    
    End Module
    Attached Images Attached Images  

  9. #9
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: DGV Text File

    Ok Let's try it:

    1. In my case I didnt need any special handling of line breaks. So I simply replaced them with "; ". Here we need, so we will modify our procedure. We also don't need the extra line break at the end of line, since we will be using IO.File.WriteAllLines which puts that line break automatically.
    So we modify our procedure as follows:
    vb.net Code:
    1. '' We use some sequence of non-printing characters to replace the line breaks.
    2. '' You can change these if any of these characters can be part of your regular text.
    3. Const MyCrlfMark As String = ChrW(164) & ChrW(165) & ChrW(166)
    4.  
    5. '' This function converts our text to CSV compliant text
    6. Function StringToCsvFormat(ByVal ParamArray fields() As String) As String
    7.     Dim output As String = ""
    8.     For Each field In fields
    9.         If String.IsNullOrEmpty(field) Then
    10.             field = ""
    11.         ElseIf field.Contains("""") Then
    12.             field = """" & field.Replace("""", """""") & """"
    13.         ElseIf field.Contains(",") Then
    14.             field = """" & field & """"
    15.         End If
    16.         field = field.Replace(vbCrLf, MyCrlfMark).Replace(vbCr, MyCrlfMark).Replace(vbLf, MyCrlfMark)
    17.         output &= field.Trim & ","
    18.     Next
    19.     ' -- output &= vbCrLf
    20.     Return output
    21. End Function
    22.  
    23. '' This function puts back the line breaks after we get our saved data back from disk.
    24. Function CsvToStringFormat(ByVal field As String) As String
    25.     Return field.Replace(MyCrlfMark, vbCrLf)
    26. End Function

    2. Next we use our StringToCsvFormat to when saving file.
    vb.net Code:
    1. Dim Rows = (From row In DataGridView1.Rows _
    2.             Where Not DirectCast(row, DataGridViewRow).IsNewRow _
    3.             Let RowItem = StringToCsvFormat(Array _
    4.               .ConvertAll( _
    5.               DirectCast(row, DataGridViewRow).Cells.Cast(Of DataGridViewCell).ToArray, _
    6.               Function(c As DataGridViewCell) _
    7.                 If(c.Value Is Nothing, "", c.Value.ToString))) _
    8.             Select RowItem).ToArray
    9.  
    10. IO.File.WriteAllLines(tbDGVName.Text, Rows)

    3. When loading the data, we restore our line breaks:
    vb.net Code:
    1. While Not MyReader.EndOfData
    2.     Try
    3.         Line = MyReader.ReadFields()
    4.  
    5.         '' restore the line breaks
    6.         For i = 0 To line.Length - 1
    7.             Line(i) = CsvToStringFormat(Line(i))
    8.         Next
    9.  
    10.         ' For every column per line
    11.         ' there must be a column in the DataGridView
    12.         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)})
    13.         sender.EndEdit()
    14.         ' 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)})
    15.     Catch ex As FileIO.MalformedLineException
    16.         Errors.Add(ex.Message)
    17.     Catch ex As Exception
    18.         Errors.Add(ex.Message)
    19.     End Try
    20. End While

    (NB: None of the above code is tested.)
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  10. #10

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: DGV Text File

    Fantastic! Thank you ever so much! That works absolutely perfectly - not an error anywhere. Superb!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width