我有一个方法:
问题(互连在一起):
你有什么建议吗?谢谢!
Private Function CancelDueToUnsaved() As Boolean
If Not _data.Modified Then Return False
Dim answ = MsgBox("Save changes?", MsgBoxStyle.YesNoCancel + MsgBoxStyle.Question, "")
If answ = MsgBoxResult.Yes Then SaveData()
Return (answ = MsgBoxResult.Cancel)
End Function
Private Sub Form_Closing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If CancelDueToUnsaved() Then e.Cancel = True
End Sub
答案 0 :(得分:0)
我会将其命名为“SaveChanges”(如Tom所提到的),因为它应该显示保存数据操作在此处发生。如果重要的话,命名参数也可以提高可读性:
Private Sub SaveChanges(ByRef cancelled as Boolean)
...
End Sub
你也可以抛出自定义异常,但对于一个布尔值来说太多了:
Private Sub SaveChanges()
...
If answ = MsgBoxResult.Cancel Then Throw New UserCancelException
...
End Sub
答案 1 :(得分:0)
我认为这是一种非常普遍的情况;在我的表格中,我已经解决了使用两个函数:
Function SaveChanges() As Boolean
SaveChanges = False
'check if data compiled is ok
'save changes under transaction
'(...)
'if everything is ok
SaveChanges = True
End Function
Function blnExitMode() As Boolean
blnExitMode = True
'code to check if there are changes to save
'(...)
'if there are changes to save
Select Case MsgBox("Save changes?", MsgBoxStyle.Question + MsgBoxStyle.YesNoCancel + MsgBoxStyle.DefaultButton3)
Case MsgBoxResult.Yes
If Not Me.SaveChanges Then blnExitMode = False
Case MsgBoxResult.Cancel
blnExitMode = False
End Select
End Function
所以我可以在表单关闭时使用此代码:
If Not Me.blnExitMode Then e.Cancel() = True
当用户尝试移动到其他记录而不保存更改或更改表单时,我也可以致电blnExitMode
'模态' (即从插入到搜索)。
答案 2 :(得分:0)
看起来您只是说“当表单关闭时,如果更改已经保存,则提示用户是否保存或不关闭表单。如果是,保存更改并关闭,如果不,不要保存,但不管怎样,如果取消,请不保存或关闭。“是
您可以在表单关闭事件本身内轻松完成此操作,而不是调用其他内容并尝试传递响应(由于您尝试使用布尔值但有3个选项,因此您的要点有点困难。)< / p>
这就是我自己完成这项工作的方法......希望这会有所帮助:
Private Sub Form_Closing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If _data.Modified Then
Dim dialogResult = MessageBox.Show(Me, "Changes have been made. Would you like to save?", "Unsaved Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If dialogResult = System.Windows.Forms.DialogResult.Yes Then
SaveData()
ElseIf dialogResult = System.Windows.Forms.DialogResult.Cancel Then
e.Cancel = True
Else
'result is No - don't do anything...just let the form close
End If
End If
End Sub
答案 3 :(得分:0)
[解决]
注意:如果单击“重置”按钮,我也一直在使用此代码,其中一个简单的问题确定/取消更适合。但无论如何我放弃了按钮,因为它没有多大意义。因此,HandleUnsavedChanges方法现在实际上可以在Form.Close()事件中传输。
Private Sub HandleUnsavedChanges(ByRef userCancelled As Boolean)
If Not _data.IsModified Then Exit Sub
Dim answ = MsgBox(msg, MsgBoxStyle.YesNoCancel + MsgBoxStyle.Question, "Bestätigung")
Select Case answ
Case MsgBoxResult.Yes
SaveData()
Case MsgBoxResult.Cancel
userCancelled = True
End Select
End Sub
Private Sub Form_Closing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
HandleUnsavedChanges(userCancelled:=e.Cancel)
End Sub