I am currently working on a program to track my mile for my monthly expense report for work. Everything is working great, however, I can not for the life of me find a code to write 8 lines from the text file back into the listview on my form. I have found some samples that work for 2 to 4 columns, but not for 8. My code for saving the file is as follows:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim sfile As New SaveFileDialog
        With sfile
            .Title = "Choose your path to save the information"
            .InitialDirectory = "D:\"
            .Filter = ("ONLY Text Files (*.txt) | *.txt")
        End With

        If sfile.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Dim Write As New IO.StreamWriter(sfile.FileName)
            Dim k As ListView.ColumnHeaderCollection = ListView1.Columns
            For Each x As ListViewItem In ListView1.Items
                Dim StrLn As String = ""
                For i = 0 To x.SubItems.Count - 1
                    StrLn += k(i).Text + " :" + x.SubItems(i).Text + Space(3)
                Next
                Write.WriteLine(StrLn)
            Next
            Write.Close() 'Or  Write.Flush()
        End If

        Me.Close()
    End Sub

I just need help with writing everything back into the listview when the form loads. I have not had any luck with this part.

Thank you,
Kenneth

Dani AI

Generated

Short plan: read each text line, extract the "Header :Value" pairs and use only the Value parts to build a ListViewItem with 8 subitems. The snippet below uses a regular expression that looks for "something :value" followed by three spaces or end-of-line — that matches the format your save code produces and tolerates headers with spaces.

' Requires: Imports System.Text.RegularExpressions
Private Sub LoadListViewFromFile(filePath As String)
    If Not IO.File.Exists(filePath) Then Return
    ListView1.BeginUpdate()
    Try
        ListView1.Items.Clear()
        Dim pattern As String = "([^:]+)\s*:\s*([^:]+?)(?=\s{3}|$)"
        For Each line As String In IO.File.ReadAllLines(filePath)
            If String.IsNullOrWhiteSpace(line) Then Continue For
            Dim matches As System.Text.RegularExpressions.MatchCollection =
                System.Text.RegularExpressions.Regex.Matches(line, pattern)
            Dim values As New List(Of String)
            For Each m As System.Text.RegularExpressions.Match In matches
                values.Add(m.Groups(2).Value.Trim())
            Next
            While values.Count < 8
                values.Add(String.Empty)
            End While
            Dim lvi As New ListViewItem(values(0))
            For i As Integer = 1 To 7
                lvi.SubItems.Add(values(i))
            Next
            ListView1.Items.Add(lvi)
        Next
    Finally
        ListView1.EndUpdate()
    End Try
End Sub

Notes and troubleshooting: ensure ListView1.View = View.Details and that you have the 8 columns created in the same order you expect. If a line can have fields in different orders (or extra/missing fields), parse each segment into a Dictionary(of String,String) by splitting on three spaces, split each segment at the first ":" and use the left side as the header key; then populate subitems by looking up ListView1.Columns(i).Text in the dictionary — this is more robust than relying solely on position. Trim values, and convert date/mileage/expense text to the appropriate types after loading (parse currency and remove the "$" before Decimal.Parse).

Longer term: is right — move to a DataTable/DataGridView backed by a small DB (SQLite or LocalDB) when you want search/edit. Keep file/DB read-write code isolated as suggested. And as noted, regex/delimiters are the right tools while you stick with text files.

Recommended Answers

All 9 Replies

And what is your code for loading the file?
"Not having any luck" tells us very little.
Do you get errors, explain what's happening.
Please specify.

You can read this link to read a text file to get the lines.

So the thing is I am having problems figuring out what the code should be, I need help with how to start the process. Everything I have looked at confuses me. If someone can point me in the right direction it would help me out alot.

The way my code saves my data to the text file looks like this:

Vehicle :Toyota Sienna Date :1/1/2018 Starting Location :Office Starting Mileage :123 Destination :Waco ISD Ending Mileage :125 Total Mileage :2 Expense :$0.68
Vehicle :Toyota Sienna Date :1/1/2018 Starting Location :Waco ISD Starting Mileage :125 Destination :Office Ending Mileage :127 Total Mileage :2 Expense :$0.68
Vehicle :Toyota Sienna Date :1/1/2018 Starting Location :Office Starting Mileage :127 Destination :City of Waco Ending Mileage :129 Total Mileage :2 Expense :$0.68

What I need to do is add the data behind the : back into the listbox. Is there a way to do that? I do not want to add all the information like Vehicle :Toyota Sienna I just want to add Toyota Sienna. If this make sense.

I think I want to change my code from saving into a text file to being saved into a database.

I think your first step would be to get familiar with DataTables and the DataGridView control. These were specifically designed for viewing and editing the data to and from an SQL based database. There are plenty pf free tutorials that will help with this.

Thank you, I will be looking into that soon. I eventually want to be able to search and edit entries that is why I decided to change from a text file to a database. I am fairly new to programming and would like to learn more about saving to databases

Its a good idea to do database but if your data is not too big and you don't worry that much with data loos then you can still continue with text file but since you are new I think you will have to read more in file streams, IO, just to name a few and there are ways also to search for data using also regex and delimitors and Array. I think thats what you need to look into.

I suggest you isolate your database read/write code in separate modules. That will make it easier to transition from one data source to another. The only code you would have to change would be isolated in one or two modules. You could start with a json, xml, or even csv file, get your app working, then move to an actual database at a later point.

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.