I need to save a file from different locations in my application, so I created a sub for that; everything work just fine, except when a user clicks cancel when the save dialog shows up; if user clicks "Cancel", the form will close; I tried the TWO Options shown in the code below but both did not work; any suggestion will be appreciated:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SaveFileDialog()
End Sub
Sub SaveFileDialog()
SaveFileDialog1.Filter = "TXT Files (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
'If SaveFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
Dim MekdamSaveFile = SaveFileDialog1.FileName
System.IO.File.WriteAllText(MekdamSaveFile, "")
My.Computer.FileSystem.WriteAllText(MekdamSaveFile, RichTextBox2.Text, True)
End If
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim result = MessageBox.Show("The File: has been changed, do you want to save it? ", _
"Mekdam Message 701", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If result = DialogResult.Cancel Then
e.Cancel = True
ElseIf result = DialogResult.No Then
'PROCEED...
ElseIf result = DialogResult.Yes Then
SaveFileDialog()
End If
End Sub
End Class
Make your SaveFileDialog Subroutine into a Function, then return False if anything other than OK was done, then test it in your FormClosing EventHandler and stop the Close.
Modified SaveFileDialog
Function SaveFileDialog() As Boolean
SaveFileDialog1.Filter = "TXT Files (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
'If SaveFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
Dim MekdamSaveFile = SaveFileDialog1.FileName
System.IO.File.WriteAllText(MekdamSaveFile, "")
My.Computer.FileSystem.WriteAllText(MekdamSaveFile, RichTextBox2.Text, True)
Return True 'Return True if Ok is clicked
Else
Return False 'return false this will give you something to conditionaly test
End If
End Function
Modified FormClosing EventHandler
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim result = MessageBox.Show("The File: has been changed, do you want to save it? ", _
"Mekdam Message 701", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If result = DialogResult.Cancel Then
e.Cancel = True
ElseIf result = DialogResult.No Then
'PROCEED...
ElseIf result = DialogResult.Yes Then
If Not SaveFileDialog() Then e.Cancel = True 'this will abort the close
End If
End Sub
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments