Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: Expense Tracker

Build a VB.NET expense tracker step by step - model, service layer, LINQ summaries, CSV persistence, a WinForms front end (read-only) and a fully runnable C# stand-in of the core logic.

Time to combine what you have learned: classes, collections, LINQ, files and a Windows Forms front end. The project is an expense tracker: record expenses with a date, category, description and amount; see totals per category and per month; save to and load from a CSV file.

Honest limits. The VB.NET compiler and Windows Forms cannot run on this site. The VB code for the model and the form is read-only and no window output is claimed. The core logic (model, service, LINQ reports, CSV round trip) is given as runnable C# stand-ins that perform the same operations with the same .NET classes. Port them to VB line by line using the comparison table.

The design

Separate three layers so the logic never depends on the window.

flowchart LR
    F["MainForm (UI, WinForms)"] --> S["ExpenseService (rules, reports)"]
    S --> R["ExpenseStore (CSV file)"]
    S --> M["Expense (model)"]

The form calls the service; the service uses the store; only the form knows about controls.

Piece Responsibility
Expense One record: Id, Date, Category, Description, Amount
ExpenseStore Load and save a list of expenses (CSV)
ExpenseService Add, remove, validate, summarize
MainForm Show a grid, an entry panel and totals

Step 1: the model

VB
Public Class Expense
    Public Property Id As Integer
    Public Property [Date] As Date
    Public Property Category As String
    Public Property Description As String
    Public Property Amount As Decimal
End Class

Use Decimal for money, never Double: binary floating point cannot represent 0.10 exactly, so sums drift. [Date] needs brackets because Date is a VB keyword.

Step 2: the service, with validation and reports

VB
Public Class ExpenseService
    Private ReadOnly _items As New List(Of Expense)
    Private _nextId As Integer = 1

    Public Function Add(d As Date, category As String, description As String, amount As Decimal) As Expense
        If amount <= 0D Then Throw New ArgumentOutOfRangeException(NameOf(amount), "Amount must be positive")
        If String.IsNullOrWhiteSpace(category) Then Throw New ArgumentException("Category is required")
        Dim e As New Expense With {.Id = _nextId, .Date = d, .Category = category.Trim(),
                                   .Description = description, .Amount = amount}
        _nextId += 1
        _items.Add(e)
        Return e
    End Function

    Public Function TotalsByCategory() As IEnumerable(Of (Category As String, Total As Decimal))
        Return From e In _items
               Group e By e.Category Into Total = Sum(e.Amount)
               Order By Total Descending
               Select (Category, Total)
    End Function
End Class
C# The tracker core (C# stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Step 3: persistence in CSV

The store writes one line per expense and reads them back. Invariant culture keeps the decimal point and date format stable on every PC, which matters when a German user saves a file that an American user opens.

VB
Public Class ExpenseStore
    Public Shared Sub Save(path As String, items As IEnumerable(Of Expense))
        Dim lines = items.Select(Function(e) String.Join(",", e.Id,
                         e.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
                         e.Category, e.Description.Replace(",", " "),
                         e.Amount.ToString(CultureInfo.InvariantCulture)))
        File.WriteAllLines(path, lines)
    End Sub
End Class
C# Save and load round trip (C# stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

(Commas inside descriptions would break this tiny format, so the sample replaces them with spaces. A real app would quote fields or use JSON as in JSON and XML.)

Step 4: the WinForms front end (read-only)

Lay out the form with a docked DataGridView (Fill), a top panel for entry (date picker, category combo box, description text box, amount NumericUpDown, Add button) and a StatusStrip for the total. The handlers stay thin and only call the service.

VB
Public Class MainForm
    Private ReadOnly _svc As New ExpenseService()
    Private ReadOnly _bindingList As New BindingList(Of Expense)

    Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        cboCategory.Items.AddRange({"Food", "Transport", "Fun", "Bills"})
        grid.DataSource = _bindingList
    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Try
            Dim item = _svc.Add(dtpDate.Value.Date, cboCategory.Text, txtDesc.Text, nudAmount.Value)
            _bindingList.Add(item)
            tslTotal.Text = "Total: " & _bindingList.Sum(Function(x) x.Amount).ToString("C")
            txtDesc.Clear() : nudAmount.Value = 0
        Catch ex As ArgumentException
            MessageBox.Show(ex.Message, "Cannot add", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub
End Class

Extension ideas

  1. Delete and edit rows; keep Id stable.
  2. A filter by month and category using a BindingSource.Filter or LINQ.
  3. A monthly budget per category with a warning when exceeded.
  4. Export the report to a text file; import a bank CSV.
  5. Add unit tests for ExpenseService (no window needed, thanks to the layers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use Decimal for money?

    Binary floating point cannot represent values like 0.1 exactly; Decimal can.
  2. 2. Why keep rules in ExpenseService instead of the button handler?

    Layering makes logic independent of the UI.
  3. 3. Why use InvariantCulture when saving numbers and dates to a file?

    Culture-specific formats (decimal comma, date order) would break loading on another PC.
  4. 4. Why is [Date] written in brackets in VB?

    Square brackets let you use a reserved word as a name.

Summary

  • Three layers (form, service, store) keep logic testable and the UI thin.
  • Decimal for money; validate in the service; summarize with LINQ Group By.
  • Save with invariant culture; consider JSON or quoted CSV for real data.
  • Handlers only gather input, call the service and show the result.

Next: Project: Grade Book