Save Dialog when User Cancel - vb.net

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

Is not too much clear what you need... try this:
Public Class Form1
Private Sub Test() Handles MyBase.Load
Do Until Not ShowSaveFileDialog() = DialogResult.Cancel
ShowSaveFileDialog()
Loop
End Sub
Private Function ShowSaveFileDialog() As DialogResult
Using SFD As New SaveFileDialog With
{
.Filter = "TXT Files (*.txt)|*.txt",
.ValidateNames = True
}
AddHandler SFD.FileOk, AddressOf SFD_FileOk
Return SFD.ShowDialog()
RemoveHandler SFD.FileOk, AddressOf SFD_FileOk
End Using
End Function
Private Sub SFD_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs)
IO.File.AppendAllText(sender.FileName, RichTextBox2.Text, System.Text.Encoding.Default)
End Sub
End Class

Related

opendialog to show a file and save it with checkbox vb.net

I'm trying to connect to a database (mdb file of my choice) in a login screen and i want to save it for faster logon next times i boot the software.
I click on choose database button, opendialog lets me choose the file, i click OK and the db location shows in a textbox.
there's a checkbox beneath to save it before i connect to it.
But i can't manage to keep the checkbox checked, nor the textbox filled after i restart te program.
here's my current code:
Public Class LoginScreen
Private Sub Loginscreen_load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Visible = False
Panel1.Visible = False
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
Private Sub btnExit2_Click(sender As Object, e As EventArgs) Handles btnExit2.Click
Application.Exit()
End Sub
Private Sub tmrLogin_Tick(sender As Object, e As EventArgs) Handles tmrLogin.Tick
ProgressBar2.Value = ProgressBar2.Value + 20
lblLoginMessages.Text = ProgressBar2.Value & "%" & " Completed"
If ProgressBar2.Value >= 100 Then
tmrLogin.Enabled = False
If txtUser.Text = "azert" And txtPassword.Text = "azert" Then
ProgressBar2.Value = 0
Else
lblLoginMessages.Text = "Wrong credentials, Try again!"
pboxClosed.Visible = True
PboxOpen.Visible = False
ProgressBar2.Value = 0
txtPassword.Text = ""
txtUser.Text = ""
End If
End If
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
ProgressBar2.Visible = True
tmrLogin.Enabled = True
pboxClosed.Visible = False
PboxOpen.Visible = True
''navraag doen om dit correct in te stellen! ! ! ! !!
'If ProgressBar2.Value = 100 Then
'lblLoginMessages.Text = "Logging in..."
Me.Hide()
Mainscreen.Show()
'End If
If chkSavePassword.Checked = True Then
My.Settings.databaselocation = txtDatabaselocationshow.Text
My.Settings.SaveLocation = True
End If
End Sub
Private Sub btnDBConnect_Click(sender As Object, e As EventArgs) Handles btnDBConnect.Click
If Panel1.Visible = False Then
Panel1.Visible = True
Else
Application.Exit()
End If
End Sub
Private Sub btnChoose_Click(sender As Object, e As EventArgs) Handles btnChoose.Click
Dim strtext As String
OpenFileDialog1.Filter = "Database Files | *.mdb"
OpenFileDialog1.InitialDirectory = "F:\GoogleDrive\EINDWERK VBNET"
OpenFileDialog1.Title = "Choose your Database"
OpenFileDialog1.ShowDialog()
strtext = OpenFileDialog1.FileName
txtDatabaselocationshow.Text = strtext
'If OpenFileDialog1.ShowDialog = DialogResult.OK Then
' strtext = OpenFileDialog1.FileName
' txtDatabaselocationshow.Text = strtext
'Else
' MsgBox("Error: the database file could not be read, try again.")
'End If
End Sub
Private Sub tmrshowloginpanel_Tick(sender As Object, e As EventArgs) Handles tmrshowloginpanel.Tick
Panel1.Width += 5
If Panel1.Width >= 700 Then
tmrshowloginpanel.Stop()
End If
End Sub
End Class
i've scoured the net but can't really find what to do?
if you need more information, shoot!
Walk through this with me:
Make a new project, one form, add a textbox and a combobox.
Click the textbox:
In the properties grid at the top click (Application Settings), then the 3 dots next to Property Binding. Scroll to Text. Drop down the setting and choose New at the bottom.
Give it a name of ChosenDatabasePath or something useful and descriptive like that
Repeat from "Click the textbox" for the checkbox instead, and this time bind the Checked property not the Text property.. Call the checkbox's Checked binding SavePassword or similar
Close all the dialogs so you're back at the form
Click anywhere on the background of the form when switch to Events in the property grid, find FormClosing and double click it
Put My.Settings.Save() in the FormClosing event handler
Run the app, write something in the textbox, close the form (by the X, not by stopping debugging), then immediately open the app again (run it)

vb.net formclosing with dialog

I can not believe I am asking this question after reading similar questions mostly OLD and here is the frustration I had code that worked just as desired then I changed to Option Strict ON now more issues than I bargained for
Here is the code that works OR I should say worked at one time
In fact it still works on another test project?
The Handles Me.Closing has a RED ERROR squiggle line under it
Private Sub frmTwo_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.Closing
Const message As String = "YES Exit Program" + vbCrLf + vbNewLine + "NO Back to Form Start"
Const caption As String = "Exit OR Cancel"
Dim result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
Application.Exit()
ElseIf result = DialogResult.No Then
frmStart.Show()
Me.Hide()
'tbMessage.Text = "CANCEL"
e.Cancel = True
End If
End Sub
Tested this code on two forms frmStart and frmTwo on frmTwo it does not stop Debugging
Private Sub frmStart_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
If MessageBox.Show("Are you sure to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
e.Cancel = False
Else
Me.Hide()
frmTwo.Show()
e.Cancel = True
End If
End Sub
It seems with Option Strict ON VB.Net does not like constructing the Sub this way
Private Sub frmStart_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
And as mentioned you then need to include Imports System.ComponentModel
So to STOP playing e.Cancel = True and e.Cancel = False just write a Sub as seen below and Call that Sub from some Button no need for Imports System.ComponentModel
Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
CloseForm()
End Sub
Public Sub CloseForm()
Const message As String = "YES Exit Program" + vbCrLf + vbNewLine + "NO Return to Form Start"
Const caption As String = "Exit OR Return"
Dim result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
Application.Exit()
ElseIf result = DialogResult.No Then
Close()
frmStart.Show()
End If
End Sub
Recreating the closing event, the event parameters are (sender As Object, e As CancelEventArgs) not the different types. I'm testing this against .Net Framework 4.8, what .Net are you targeting?
This worked as expected:
Private Sub frmStart_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
Const message As String = "YES Exit Program" + vbCrLf + vbNewLine + "NO CANCEL"
Const caption As String = "Exit OR Cancel"
Dim result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.No Then
Me.Text = "CANCEL"
e.Cancel = True
End If
End Sub

VB messagebox yes/no I want the 'no' to close message box, but its closing the form i want open

Private Sub btnMain_Click(sender As Object, e As EventArgs) Handles btnMain.Click
Dim result As DialogResult = MessageBox.Show("Did you save customer info?", "Save Information", MessageBoxButtons.YesNo, MessageBoxIcon.Stop)
If (result = DialogResult.Yes) Then
'Me.Visible = False
Me.Close()
frmDuneTours.Visible = True
ElseIf (result = DialogResult.No) Then
frmDuneTours.Visible = False
Me.Visible = True
End If
End Sub
When you place Me.Close before
frmDuneTours.Visible = True
the second line never executes because when you close the current form the application ends.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim result As DialogResult = MessageBox.Show("Did you save customer info?", "Save Information", MessageBoxButtons.YesNo, MessageBoxIcon.Stop)
If (result = DialogResult.Yes) Then
frmSortedList.Visible = True
Me.Close()
ElseIf (result = DialogResult.No) Then
frmSortedList.Visible = False
End If
End Sub

Alternatives for 'Handles Me.FormClosing' in modules

I would like to know of any alternatives to the 'Handles Me.FormClosing' in modules.
I have created code that will display a confirmation message upon clicking the 'X' button. The issue is, I need to put this code into a module to use on multiple forms where i can call it, however, when I attempt to do this the 'Handles Me.FormClosing' will not work.
Here is the code i am using:
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
FrmLogin.Close()
Else
e.Cancel = True
End If
End Sub
Whenever you create a new form:
Dim newForm as Form = New YourFormClass()
AddHandler newForm.FormClosing, AddressOf YourModule.Close
This will route all closing events you want through that sub. Then just remove the Handles Me.Closing unless there is something you aren't showing us that makes it relevant.
Try This. I made changes to work as you want :
Module YourModule
Public Function AskFormClosing() As Boolean
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
Return True
Else
Return False
End If
End Function
End Module
And then
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If YourModule.AskFormClosing Then
Application.Exit
Else
e.Cancel = True
End If
End Sub
One possibility ist to create a function in your module which shows the MessageBox and exits Application if "Yes" is clicked else returns False.
Module YourModule
Private dontAskAgain As Boolean
Public Function AskFormClosing() As Boolean
If dontAskAgain = False Then
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
dontAskAgain = True
Application.Exit()
End If
End If
Return dontAskAgain
End Function
End Module
And then you only need to set e.Cancel to the inverted result of the function.
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = Not YourModule.AskFormClosing
End Sub
If you prefer to use AddHandler as suggested by other people, you could use the following method that will lead to the same result.
Module YourModule
Public Sub AskFormClosing(sender As Object, e As FormClosingEventArgs)
If dontAskAgain = False Then
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
dontAskAgain = True
Application.Exit()
Else
e.Cancel = True
End If
End If
End Sub
End Module
And then add the Handler like this:
Dim newForm as Form = New YourFormClass()
AddHandler newForm.FormClosing, AddressOf YourModule.AskFormClosing
But for your main-Form you will need to add the Handler in the Loading Event, like this:
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Me.FormClosing, AddressOf YourModule.AskFormClosing
End Sub
Rather than placing this code in a module for reuse, consider create a base Form that has the behaviour you wish to share and then have you other forms inherit from this base Form (rather than from System.Windows.Forms.Form).
See How to: Inherit Windows Forms on the Microsoft website.

Is there any way to hide a MessageBox?

Is there any way to hide a MessageBox at form load?
I have used Checkedlistbox, and already there is a checkeditems on load of a Form2.
What I want to do is, when I click Form1 it shows Form2 with Checkedlistbox. My problem is, when I click Form1, it show up MessageBox before Form2.
Here is my code on vb.net:
On Form1:
Private Sub cmdSubmitModifyQuant_Click(sender As Object, e As EventArgs) Handles cmdSubmitModifyQuant.Click
Form2.Show()
End Sub
On Form2:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
chklstBox1Fill()
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
If e.NewValue = CheckState.Checked Then
question = MsgBox("Area you sure you want to remove?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Message")
If question = MsgBoxResult.Yes Then
'Nevermind
ElseIf question = MsgBoxResult.No Then
e.NewValue = CheckState.Checked
End If
End If
End Sub
In my code you can see that i also need to check checklistbox1.
This issue is probably that inside the chklstBox1Fill method you are checking items in your check box list, this causes the event to raise that shows the checkbox. One way to avoid this would be to set a flag to indicate you are populating the list and not show the message box when the flag is set:
Private FillingList As Boolean
Private Sub chklstBox1Fill()
FillingList = True
'Rest of method here.
FillingList = False
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
If FillingList = True Then
Return
End If
If e.NewValue = CheckState.Checked Then
question = MsgBox("Area you sure you want to remove?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Message")
If question = MsgBoxResult.Yes Then
'Nevermind
ElseIf question = MsgBoxResult.No Then
e.NewValue = CheckState.Checked
End If
End If
End Sub
(Forgive my VB.Net, been several years since I wrote any!)
Add a boolean variable that indicates wether your load procedure is complete or not. Doing so will not execute the CheckedChanged until the variable is set to True.
Dim FormLoaded As Boolean = False
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
chklstBox1Fill()
FormLoaded = True
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
If FormLoaded = False Then Return 'Don't execute the rest of the code if it evaluates to False.
If e.NewValue = CheckState.Checked Then
question = MsgBox("Area you sure you want to remove?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Message")
If question = MsgBoxResult.Yes Then
'Nevermind
ElseIf question = MsgBoxResult.No Then
e.NewValue = CheckState.Checked
End If
End If
End Sub