Close VB.Net form without message box if textboxes are empty - vb.net

I am currently trying to fix the form closing event in VB.Net so that when there is text in txtInput1 and txtInput2 when the user tries to exit the form it will exit with a warning prompt from the message box. This works, however it should not show this prompt if there is nothing in either box, the form should just close. Here is the form close event i have so far, but it is not working:
'FormClosing Event
Private Sub MyForm_Closing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If (txtInput1.Text = "" And txtInput2.Text = "") Then
Me.Close()
End If
If MessageBox.Show("Are you sure you sure you want to exit?", "Exit", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then
e.Cancel = True
End If
End Sub

Firstly, don't call Close in the FormClosing event handler. If that event is raised then the form is already closing UNLESS you specifically prevent it, i.e. unless you set e.Cancel to True.
As for the issue, if you want to display the message ONLY IF a certain condition is true then it should be obvious that the code that displays it must be inside an If block. Think about what it is you want to do and do that. Write it down if you need to, so you have something to actually compare your code to. You want to display the message if only one TextBox is empty, so that's what you need to test for and do:
If (txtInput1.Text = String.Empty AndAlso txtInput2.Text <> String.Empty) OrElse
(txtInput1.Text <> String.Empty AndAlso txtInput2.Text = String.Empty) Then
If MessageBox.Show("Are you sure you sure you want to exit?", "Exit", MessageBoxButtons.YesNo) = DialogResult.No Then
e.Cancel = True
End If
End If
If you think a bit harder about the condition then you can simplify that code somewhat. If you create a list of the Text values from the TextBoxes then you only want to display the message if that list contains one empty String:
If {txtInput1.Text, txtInput2.Text}.Count(Function(s) s = String.Empty) = 1 Then
If MessageBox.Show("Are you sure you sure you want to exit?", "Exit", MessageBoxButtons.YesNo) = DialogResult.No Then
e.Cancel = True
End If
End If

Related

Have to Click Form To Give Focus

I have a main form with buttons that open a custom message box form. It works fine if it's just a message and the user just needs to click OK. But if the answer to that message box is important, like "Are you sure you want to delete this file?" I use a while loop to wait for the user to respond and once they do then a flag is set from false to true and the response is recorded.
For some reason any response that uses a while loop to wait is causing the message box form to not have focus after being called. Requiring the user to first click on the form, and then click on OK.
So far I've tried using form.Activate() instead of form.Show(), as well as calling Application.DoEvents() inside the while loop since I believed the while loop was taking focus away from the message form immediately after being called. Neither solved the issue.
Code from a message box that works as intended:
If cmbLoadProgram.SelectedItem = "" Then
frmMessageBox.lblHeader.Text = "Set-Up"
frmMessageBox.lblMessageText.Text = "No Program Selected!"
frmMessageBox.Show()
Exit Sub
End If
Code from a message box that needs to be clicked twice:
If btnGetHexStart.Visible = False And cmbStartCondition.SelectedItem = "Pixel" Then
frmMessageBox.lblHeader.Text = "Hex Set-Up"
frmMessageBox.lblMessageText.Text = "Reset Hex Code Data?"
frmMessageBox.Show()
Me.Hide()
While Flag = False
If frmMain.OKCancel = "OK" Then
btnGetHexStart.Visible = True
btnGetHexStart.Enabled = True
btnGetHexStart.PerformClick()
Flag = True
End If
frmMain.delay(20)
End While
End If
I'm wanting both options to only need to be clicked once in order to confirm or cancel the action. Instead of the while loop questions needing to be clicked twice.
This just an idea from me, just how to open msgboxform, here we need MessageForm and one module1, for example:
Public Class MessageForm
'You can assign any variable to show any data in messageform display
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
theResult = MsgBoxResult.Ok
Me.Close()
Me.Dispose()
End Sub
Private Sub bttcancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttcancel.Click
theResult = MsgBoxResult.Cancel
Me.Close()
Me.Dispose()
End Sub
End Class
Module Module1
Public theResult As MsgBoxResult
'You can add some parameter here to submit to MessageForm
Public Function myMessageBox() As MsgBoxResult
myMessageBox = MsgBoxResult.Cancel
MessageForm.ShowDialog()
myMessageBox = theResult
End Function
End Module
and then you can call the myMessageBox anywhere like this:
'if myMessageBox procedure have parameter, apply the paramters too
dim myRslt = myMessageBox()
You don't need to create a form,You can use DialogResult and MessageBox.Show, code:
Dim Result As DialogResult = MessageBox.Show("Set-Up" & vbCrLf & "No Program Selected!", "Warning", MessageBoxButtons.OKCancel)
If Result = DialogResult.OK Then
ElseIf Result = DialogResult.Cancel Then
End If

Message box on close only show when text is changed

So I take no credit to the following code as it was given to me by another fellow user and don't get me wrong it works great but now I only Want the message box to show when text is changed in textboxes and if all text boxes are empty to just close the app when the X is clicked.
Any help is appreciated!
'Creates _handle as boolean
Private _handle As Boolean = True
Private Sub MainWindow_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
'Creates a messagebox to ask if the user wants to exit the application or no. If yes application closes, if no then application stays open
If _handle = True Then
e.Cancel = True
Dim result = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.YesNo, MessageBoxImage.Question)
If (result = MessageBoxResult.Yes) Then
_handle = False
Environment.Exit(0)
End If
End If
End Sub

VB.NET: DialogResult.No is not closing the form

Using Message Box DialogResult.No Condition for closing the form doesnot perform as expected.
The formclosing event aske user whether to save the document or not before closing.
The following is my FormClosing event.
Private Sub PDFViewSimple_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
Handles Me.FormClosing
If doc.IsModified Then
Dim message As String = "The document is modified, would you like to save it?"
Dim caption As String = "File Not Saved"
Dim buttons As MessageBoxButtons = MessageBoxButtons.YesNo
Dim DefaultButton As MessageBoxDefaultButton = MessageBoxDefaultButton.Button1
Dim icon As MessageBoxIcon = MessageBoxIcon.Question
Dim result As DialogResult
' Displays A MessageBox.
result = MessageBox.Show(message, caption, buttons, icon, DefaultButton)
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
Me.Close()
ElseIf (result = DialogResult.No) Then
Me.Close() ''Should I replace with (Application.Exit)
End If
End If
End Sub
There's all sorts wrong with that code. Firstly, given that there are only two options, using ElseIf is pointless, although not strictly wrong. If it's not Yes then it must be No, so you'd only need an Else:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
Me.Close()
Else
Me.Close()
End If
Next, even an Else is pointless because you're calling Close regardless of the outcome. All you need to do is check for Yes, do anything specific to Yes and then call Close regardless:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
End If
Me.Close()
Finally, you shouldn't be calling Close at all. You're in the FormClosing event handler so the form is already closing. You only have to do something if you want the form to NOT close. So, all you need is this:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
End If
If you wanted the form to NOT close then you would set e.Cancel to True.

For some reason I can't close forms in my if statement?

So, I'm trying to close all forms in my app when the user reverts their settings via clicking a button, but it isn't going well, as for some reason when I try to close them nothing happens.
I have checked for output and didn't notice anything, and strangely, if I close my forms without an if statement, it works. What's up?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim result As DialogResult = MessageBox.Show("Are you sure you want to revert all your settings? There is no undo, and if you click yes, WikiFinder will restart.", "WikiFinder", MessageBoxButtons.YesNo)
If (result = DialogResult.OK) Then
My.Settings.MenuColor = System.Drawing.Color.FromArgb(248, 24, 0)
My.Settings.MenuTextColor = Color.White
My.Settings.Siggy = ""
My.Settings.Save()
WebForm.Close()
ForumSiggy.Close()
URLform.Close()
MenuForm.Close()
Me.Close()
Else
End If
End Sub
You are not entering the If block because your dialog is Yes/No not OK. Use
result= DialogResult.Yes
This would be easy to determine by debugging.

What is the best way to detect all ways of closing a form?

I have a form that i close using End several times in my code. I want to do a command to save settings when I do this called VarsToIni() which takes some public variables and saves them in an INI file. I have tried putting it in the main window's FormClosing (which stays open throughout) and this only works when you close from pressing the X button not from my End statement.
Add a new Sub and replace calls to End with calls to your new Sub:
Sub EndMe()
VarsToIni()
Application.Exit()
End Sub
Edit:
As Dan points out, End() is a bad way to close the application, Application.Exit() is preferred.
Consider using Application.Exit() instead of End. This allows FormClosing to be called no matter what (and you can handle it based on how it is being closed).
Private Sub frmMain_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
Select Case e.CloseReason
Case CloseReason.ApplicationExitCall
' This is the result of Application.Exit()
e.Cancel = False
Case CloseReason.UserClosing
' This is the result of clicking the red X
Select Case MessageBox.Show("Are you sure you wish to exit?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Case DialogResult.Yes
e.Cancel = False
Case DialogResult.No
e.Cancel = True
End Select
Case Else
e.Cancel = False
End Select
If Not e.Cancel Then
VarsToIni()
End If
End Sub
I am quite confused by your question, nonetheless:
This will close all your forms
For each x as Form in My.Application.OpenForms
'You can then put your VarsToIni() here
x.Close()
Next
Note: Add this to your import
Imports System.Windows.Forms