We will use a global variable changed that is Boolean. Intitially, we will set it to false. We will change the value under the following conditions:
- When we add to the list box: changed=True
- When we delete from the list box: changed=True
- When we save or save as a file: changed=False
We must check to see if there are any changes when we:
- Select New
- Select open
- Select Exit
- Close the program with the X in the top right corner.
Add the variable changed to the global variables:
Public Class Form1
Dim currentFile As String
Dim Changed As Boolean = False
Because we will ask if they want to save from more than one place (when we remind them to save) we have written asktosave as a general function. That is, it is not a procedure that receives some event arguments as its parameters. It must be a function so that it can return that information to the calling procedure.
Code for AskToSave
Private Function AskToSave() As Boolean
Dim Answer As MsgBoxResult
Dim okToClear As Boolean = False 'will be the return value
If Changed Then
Answer = MsgBox("Do you want to save?", _
MsgBoxStyle.YesNoCancel + MsgBoxStyle.Question, "Save")
If Answer = MsgBoxResult.Yes Then
SaveList()
okToClear = True
End If
If Answer = MsgBoxResult.No Then
okToClear = True 'clear the list box without saving
End If
If Answer = MsgBoxResult.Cancel Then
okToClear = False
End If
End If
'if changed is false, then false is returned
Return okToClear
End Function 'AskToSave