The List Manager Project: Saving the File

When the user clicks the save menu item, we will open a file for output and write all of the items in the list box to the file.

We have created a variable currentFile that is global. That means that is it declared outside of any function or sub, usually the global variables are the first thing inside the class:

Add a global variable currentFile:

Public Class Form1
    Dim currentFile As String
Because we are going to save from more than one place (when we remind them to save) we have written savefile as a general procedure. That is, it is not a procedure that receives some event arguments as its parameters.
    Private Sub SaveList()
        Dim S As String
        Dim Num As Integer
        If currentFile = "" Then
            SaveFileDialog1.ShowDialog()
            currentFile = SaveFileDialog1.FileName
        End If
        If currentFile <> "" Then
            FileOpen(1, currentFile, OpenMode.Output)
            For Num = 0 To ListBox1.Items.Count - 1
                S = ListBox1.Items.Item(Num)
                PrintLine(1, S)
            Next Num
            FileClose(1)
            MsgBox("Items saved: " & ListBox1.Items.Count)
        End If
    End Sub 'SaveList
    

See the complete code at this point.
INDEX, Introduction, Build the Menu, Add items to a listbox, Delete items from the listbox, Save: Write the contents of the list box to a file, Open File: Read file and add to list box, Ask the user if he wants to save, When to ask the user if he wants to save, The User closes the program
Next lesson: List Manager application Finishing Touches

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Save: Write the contents of the list box to a file