Hi, Daniweb members
i have an listview containing an normal listviewitem plus one subitem
What i want to do is save the info in the listview in a textfile and load when i start my program. So that all the info will be saved, but how do i do this?

Hope somebody can help me, Killerbeat

Dani AI

Generated

’s sample is a great quick win for a 2-column WinForms ListView. If you later type a # in an item/subitem or add more columns, the simple split can break. Also, writing to C:\ may fail on newer Windows due to permissions. Below is a drop-in approach that saves to the user’s LocalAppData, quotes fields like CSV (so commas, #, and newlines are safe), and restores any number of subitems.

Place these helpers in your form, make sure your columns are created before loading (Details view), then call LoadListView(ListView1) on form load and SaveListView(ListView1) on form closing.

' Put in your form class
Private ReadOnly saveFile As String =
    IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    "YourApp", "listview.csv")

Private Sub SaveListView(lv As ListView)
    IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(saveFile))
    Using sw As New IO.StreamWriter(saveFile, False, System.Text.Encoding.UTF8)
        For Each li As ListViewItem In lv.Items
            Dim cols As Integer = Math.Max(1, lv.Columns.Count)
            Dim fields(cols - 1) As String
            fields(0) = li.Text
            For i As Integer = 1 To cols - 1
                fields(i) = If(i < li.SubItems.Count, li.SubItems(i).Text, "")
            Next
            sw.WriteLine(ToCsv(fields))
        Next
    End Using
End Sub

Private Function ToCsv(fields() As String) As String
    For i As Integer = 0 To fields.Length - 1
        Dim s As String = If(fields(i), "")
        s = s.Replace("""", """""")
        fields(i) = """" & s & """"
    Next
    Return String.Join(",", fields)
End Function

Private Sub LoadListView(lv As ListView)
    If Not IO.File.Exists(saveFile) Then Return
    lv.Items.Clear()
    Using p As New Microsoft.VisualBasic.FileIO.TextFieldParser(saveFile)
        p.SetDelimiters(",") : p.HasFieldsEnclosedInQuotes = True
        While Not p.EndOfData
            Dim f() As String = p.ReadFields()
            If f Is Nothing OrElse f.Length = 0 Then Continue While
            Dim li As New ListViewItem(f(0))
            For i As Integer = 1 To f.Length - 1
                li.SubItems.Add(f(i))
            Next
            lv.Items.Add(li)
        End While
    End Using
End Sub

Tip: if you later change the column order/count, consider versioning the file name, or clear/rebuild it to keep values aligned.

Recommended Answers

All 3 Replies

See if this helps.
Prerequisites: 1 ListView, 1 Button.

Public Class Form1

    Private myCoolFile As String = "C:\test.txt" '// your file.

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim myWriter As New IO.StreamWriter(myCoolFile)
        For Each myItem As ListViewItem In ListView1.Items
            myWriter.WriteLine(myItem.Text & "#" & myItem.SubItems(1).Text) '// write Item and SubItem.
        Next
        myWriter.Close()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ListView1.View = View.Details : ListView1.Columns.Add("column 1") : ListView1.Columns.Add("column 2")

        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.
                Dim lineArray() As String = line.Split("#") '// separate by "#" character.
                Dim newItem As New ListViewItem(lineArray(0)) '// add text Item.
                newItem.SubItems.Add(lineArray(1)) '// add SubItem.
                ListView1.Items.Add(newItem) '// add Item to ListView.
            Next
        End If
    End Sub

    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.
        newItem.SubItems.Add("subitem " & i) '// add SubItem.
        ListView1.Items.Add(newItem) '// add Item to ListView.
        i += 1
    End Sub
End Class
commented: Great Snipped, thanks +1

Thanks codeorder, it worked perfectly :D

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.