I am trying to save a listview item and 5 subitems to a txt file, I have tried one solution that was posted on here but i could not manipulate the code for all of my sub items can someone please help me out.

Dani AI

Generated

Two practical routes work reliably: keep the simple delimiter approach shown earlier, but make it delimiter-safe, or switch to a structured format (CSV with quoting, XML or JSON) for future-proofing. and demonstrated the basic idea (write each ListViewItem and its SubItems to a file and read them back). The typical failures to avoid are: using a delimiter that may appear in field text, hard-coding paths like "C:\test.txt", not handling missing subitems (IndexOutOfRange), and not disposing streams or specifying encoding.

A compact, robust pattern is CSV with proper quoting on write and a parser on read. Example (VB.NET) — quote fields that contain commas/quotes/newlines when writing, then read with TextFieldParser which understands quoted fields:

' helper to quote fields for CSV
Private Function QuoteCsv(s As String) As String
    If s Is Nothing Then s = ""
    If s.Contains("""") Or s.Contains(",") Or s.Contains(vbCr) Or s.Contains(vbLf) Then
        Return """" & s.Replace("""", """""") & """"
    End If
    Return s
End Function

' write each item: Item + 5 subitems (pad missing ones with empty strings)
' use Using for automatic disposal and UTF8 encoding

Operational notes and cautions: store the file under Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) rather than a fixed root; always use Using blocks or Try/Finally to close streams; when loading, check Fields.Length and pad to 6 fields (item + 5 subitems) to avoid IndexOutOfRange; use UTF8 to preserve characters; and consider XML/JSON serialization if you later need nested data or extra metadata (image index, Tag values). These changes keep the simple save/load approach working correctly in real-world data and across machines.

Recommended Answers

All 8 Replies

please show us your code and where exactly you stick.

Member Avatar for Member #857553
Private Sub SaveListItem(ByVal FileName As String, ByVal LI As ListViewItem)
        If String.IsNullOrEmpty(FileName) OrElse LI Is Nothing Then Exit Sub

        Dim fStream As System.IO.FileStream
        Dim sWriter As System.IO.StreamWriter

        Try
            fStream = New System.IO.FileStream(FileName, IO.FileMode.OpenOrCreate)
            sWriter = New System.IO.StreamWriter(fStream)

            For i = 0 To LI.SubItems.Count - 1
                sWriter.WriteLine(LI.SubItems(i).Text)
            Next

            sWriter.Close()
            fStream.Close()

        Catch ex As Exception

        Finally
            If fStream IsNot Nothing Then fStream.Dispose()
            If sWriter IsNot Nothing Then sWriter.Dispose()
        End Try
    End Sub

Check out this thread.
Save/Load Listview Items + Subitems

That is the one that I tried to manipulate to do 5 subposts but I could not figure it out. Can you show me the code to do 5 subposts?

Member Avatar for Member #857553

It can't be the one you tried. I wrote it a little while ago.

Tell exactly what you want and what you mean by subposts and I'll send you the code.

It can't be the one you tried. I wrote it a little while ago.

Tell exactly what you want and what you mean by subposts and I'll send you the code.

Not the code that you wrote but the code that codeorder wrote, if you would have payed attention. Look at the link that codeorder put in the post and you will see what I need but with 5 subposts.

See if this helps.

Public Class Form1

    Private myCoolFile As String = "C:\test.txt" '// your File to Save/Load from.

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        '//------ Save File ------------------------------------------\\
        Dim myWriter As New IO.StreamWriter(myCoolFile)
        For Each myItem As ListViewItem In ListView1.Items '// loop thru all items in ListView.
            With myItem
                '// write Item & "#" & SubItems... "#" is used for when loading each line and splitting it into arrays.
                myWriter.WriteLine(myItem.Text & "#" & .SubItems(1).Text & "#" & .SubItems(2).Text & "#" _
                                   & .SubItems(3).Text & "#" & .SubItems(4).Text & "#" & .SubItems(5).Text)
            End With
        Next
        myWriter.Close()
    End Sub


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '// customize ListView.
        ListView1.View = View.Details
        With ListView1.Columns
            '// .Add(column name, column width)
            .Add("column 1", 75) : .Add("column 2", 75) : .Add("column 3", 75) : .Add("column 4", 75)
            .Add("column 5", 75) : .Add("column 6", 75)
        End With
        '//------ Load File ------------------------------------------\\
        If IO.File.Exists(myCoolFile) Then '// check if File exists.
            Dim myCoolFileLines() As String = IO.File.ReadAllLines(myCoolFile) '// load your File as a string array.
            For Each line As String In myCoolFileLines '// loop thru array list of File lines.
                Dim lineArray() As String = line.Split("#") '// separate by "#" character.
                Dim newItem As New ListViewItem(lineArray(0)) '// add text Item.
                With newItem.SubItems
                    .Add(lineArray(1)) '// add SubItem 1.
                    .Add(lineArray(2)) '// add SubItem 2.
                    .Add(lineArray(3)) '// add SubItem 3.
                    .Add(lineArray(4)) '// add SubItem 4.
                    .Add(lineArray(5)) '// add SubItem 5.
                End With
                ListView1.Items.Add(newItem) '// add Item to ListView.
            Next
        End If
    End Sub

    '//------ add Items/SubItems to ListView (testing purposes only) ------------------------------------------\\
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Static i As Integer = 0
        Dim newItem As New ListViewItem("item " & i) '// add text Item.
        With newItem.SubItems
            .Add("subitem 1 - " & i) '// add SubItem 1.
            .Add("subitem 2 - " & i) '// add SubItem 2.
            .Add("subitem 3 - " & i) '// add SubItem 3.
            .Add("subitem 4 - " & i) '// add SubItem 4.
            .Add("subitem 5 - " & i) '// add SubItem 5.
        End With
        ListView1.Items.Add(newItem) '// add Item to ListView.
        i += 1
    End Sub
End Class
Member Avatar for Member #857553

Not the code that you wrote but the code that codeorder wrote, if you would have payed attention. Look at the link that codeorder put in the post and you will see what I need but with 5 subposts.

Don't need to pay attention. Don't care. Writing 5 items or "subposts" is a pretty trivial task. The code I gave you does it. Just need to do it 5 times.

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.