Visual Basic MsgBox exiting - vb.net

I created a message box which asks the user if he/she wants to close the application.
I came up with this class:
Private Sub closeAll_Click(sender As Object, e As EventArgs) Handles closeAll.Click
MsgBox("Do you want to terminate the program?", MsgBoxStyle.YesNo, "Close?")
If MsgBoxResult.Yes Then
Application.Exit()
End If
End Sub
If I select "Yes", it works fine as it exits the application successfully. But if "No" is selected, it would still close. Does it really need an "Else" statement to do so?
If it does, I don't know the proper coding for letting the program "not do something".
Can someone help?

MsgBox() is a function that returns the result (MsgBoxResult enum) so your code should be:
Private Sub closeAll_Click(sender As Object, e As EventArgs) Handles closeAll.Click
If MsgBox("Do you want to terminate the program?", MsgBoxStyle.YesNo, "Close?") = MsgBoxResult.Yes Then
Application.Exit()
End If
End Sub
The way you wrote is you take the value of enum MsgBoxResult.Yes and check if it's true. That causes an implicit conversion to a boolean value which is true since the enum value is not zero.

Related

calling event programmatically

I have a datagridview and i want to delete a row selecting the row, pressing "delete" button.
and clicking my button "cmdsave" to do so. works great.
However the code below doesn't delete the record.
what arguments do i put in cmdsave_Click(SENDER???, e???)
private Sub datagridview_UserDeletingRow(sender As Object, e As DataGridViewRowCancelEventArgs) Handles datagridvieuw.UserDeletingRow
If MsgBox("are you sure?", MsgBoxStyle.YesNo, "delete this record") = MsgBoxResult.Yes Then
cmdsave_Click(SENDER???, e???)
Else
e.Cancel = True
End If
End Sub
Private Sub cmdsave_Click(sender As Object, e As EventArgs) Handles cmdsave.Click
Me.myadapter1.Update(Me.dataset.mydatatable)
end sub
To answer the specific question you asked:
what arguments do i put in cmdsave_Click(SENDER???, e???
Anything you like; you never make use of either of the variables so you can put anything at all and it won't matter
Nothing is probably simplest
-
As you have figured out, you only call one method in the save click anyway, so it's probably simplest to just call that same method in both places

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

Application.Exit() and FormClosing event in Vb.net

I have a single windows form application that is running in system tray icon.If the user press X button of the windows form a messagebox is displayed with Yes and No ( Yes ->close the form---No->keep the form running in system tray icon).
I was thinking to prevent the scenario when the user open another instance of the application when there is already an instance running so i have used this code :
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length> 1 Then
MessageBox.Show("Another instance is running", "Error Window", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
Application.Exit()
End If
The problem is that when i want to test this the message is displayed but after i press ok, a new messagebox appears (that one from Private Sub Form_FormClosing ).If i choose NO i will have to instance running!
I have read that Application.Exit fires the Form_FormClosing event.
Is there any possibility to cancel the triggering of the Form_FormClosing event,or am i doing something wrong?
'this is the formclosing procedure
Private Sub Form_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Try
Dim response As MsgBoxResult
response = MsgBox("Are you sure you want to exit", CType(MsgBoxStyle.Question + MsgBoxStyle.YesNo, MsgBoxStyle), "Confirm")
'If the user press Yes the application wil close
'because the application remains in taskmanager after closing i decide to kill the current process
If response = MsgBoxResult.Yes Then
Process.GetCurrentProcess().Kill()
ElseIf response = MsgBoxResult.No Then
e.Cancel = True
Me.WindowState = FormWindowState.Minimized
Me.Hide()
NotifyIcon1.Visible = True
End If
PS: I am not a programmer so please don't be to harsh with me:)
You don't need to Kill the current process or use the End Statement. If you have to use these then there is something amiss with your application.
When you want to end your application use Me.Close. This will fire the FormClosing event:
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Select Case MessageBox.Show("Are you sure you want to exit?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Case Windows.Forms.DialogResult.Yes
'nothing to do here the form is already closing
Case Windows.Forms.DialogResult.No
e.Cancel = True 'cancel the form closing event
'minimize to tray/hide etc here
End Select
End Sub
To stop more than one copy of your application from running use the option to Make Single Instance Application
In the situation where you are just starting your application and are testing for previous instances I have used the VB End Statement to terminate the application.
The End statement stops code execution abruptly, and does not invoke
the Dispose or Finalize method, or any other Visual Basic code. Object
references held by other programs are invalidated. If an End statement
is encountered within a Try or Catch block, control does not pass to
the corresponding Finally block.
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length> 1 Then
MessageBox.Show("Another instance is running", "Error Window", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End
End If
Private Sub main_master_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If e.CloseReason = CloseReason.UserClosing Then
'Put you desired Code inside this!
Msgbox("Application Closing from Taskbar")
End If
End Sub
It will Close the exe from Taskbar or kill Process. If user Close the
Application from taskbar.
CloseReason.UserClosing
event will close the application if it is closed by User from
Taskber

Ok button in VB.net

I have a form that contain a combobox, I'm inserting an error check to check if the user hit the ok button before selecting a valid value from the combobox it mask the error and keep the form on focus, till the user select a proper value, but in my case after raise the error the application still close after i press Ok, would you help me identify my mistake
here is my code
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Try
If SymbolComboBox.SelectedValue Is Nothing Then
Throw New Exception()
Else
ErrorProvider1.SetError(SymbolComboBox, String.Empty)
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
End If
Catch ex As Exception
ErrorProvider1.SetError(SymbolComboBox, "Error")
End Try
End Sub
Thank you in advance
Jp
Is your OK button the default accept button for the form ? If so, I beleive it will always return System.Windows.Forms.DialogResult.OK no matter the outcome, unless you specifically cancel the action. I do not remember how to cancel the action though, but if it's the case, I sugesst you remove that AcceptButton property of your form.
OR,
Is it possible that SymbolComboBox.SelectedValue is never 'Nothing' even when nothing is selected (like an empty string) ? I would use selectedIndex instead and check if it's equal to -1.
Hope that helps.
I'm not sure, but I do know that using exceptions like this to control program flow is a bad technique, and in this case unnecessary:
Private Sub OK_Button_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles OK_Button.Click
If SymbolComboBox.SelectedValue Is Not Nothing Then
ErrorProvider1.SetError(SymbolComboBox, String.Empty)
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
Else
ErrorProvider1.SetError(SymbolComboBox, "Error")
End If
End Sub
Why not look at using a required field validator to do this? Are you doing Web forms or Win Forms development? Also what is the value of SymbolComboBox.SelectedValue when you get this issue?

Where do I control the behavior of the "X" close button in the upper right of a winform?

I'm venturing into making my VB.NET application a little better to use by making some of the forms modeless.
I think I've figured out how to use dlg.Show() and dlg.Hide() instead of calling dlg.ShowDialog(). I have an instance of my modeless dialog in my main application form:
Public theModelessDialog As New dlgModeless
To fire up the modeless dialog I call
theModelessDialog.Show()
and within the OK and Cancel button handlers in dlgModeless I have
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Hide()
End Sub
Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Hide()
End Sub
and that seems to work fine.
The "X" button in the upper right is getting me, though. When I close the form with that button, then try to reopen the form, I get
ObjectDisposedException was unhandled. Cannot access a disposed object.
I feel like I'm most of the way there but I can't figure out how to do either of the following:
Hide that "X" button
Catch the event so I don't dispose of the object (just treat it like I hit Cancel)
Any ideas?
The class of this dialog is System.Windows.Forms.Form.
Catch the FormClosing event and, if the reason is UserClosing, set Cancel on the event to true.
Something like the following:
Private Sub Form1_FormClosing(sender as Object, e as FormClosingEventArgs) _
Handles Form1.FormClosing
if e.CloseReason = CloseReason.UserClosing then
e.Cancel = true
Me.Hide()
end if
End Sub
Use Me.Close() to hide the form. To open it, use the following snippet:
If theModelessDialog.IsDisposed Then
theModelessDialog = New dlgModeless
End If
dlgModeless.Show()
If this is saving data, then you'll need to figure some way of storing it (perhaps in a static variable/s in the form). This is the proper way to do what you are trying to achieve though.
You'll also have to forgive me if my VB is off, it's been a while.
the formclosing event allows me to do a managed exit of the form so I have included a question to confirm to exit. I also have a form flag bterminate to force the cancel where i want it to and therefore not ask the question. Thanks your suggestion helped me as well :)
Dim msgboxresponse As MsgBoxResult
If e.CloseReason = CloseReason.UserClosing Then
If Not Me.bTerminate Then
msgboxresponse = MsgBox("Are you sure you want to cancel adding?", _
MsgBoxStyle.Question + MsgBoxStyle.YesNo, Me.Text)
If msgboxresponse <> MsgBoxResult.Yes Then
e.Cancel = True
Return
End If
End If
End If
#John was Hiding the form in his code and the answers above provide a solution to that case. Often, though, you are not planning to use the form again, so you really do want the form to be Disposed. All Close related activities will be in one place if you Handle the FormClosing event using Me.FormClosing by adding it to anyCancel/Close/Exit code that you already have. e.g. in #John's case:
Private Sub Cancel_Button_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Cancel_Button.Click, Me.FormClosing
....More code
Me.Dispose
End Sub
Note the use of the Me.Dispose instead of any existing Me.Close. If you leave the Me.Close you'll create an infinite loop. See this for the subtle differences between Close and Dispose.
Agree with handling the FormClosing event. Or change the properties on the form to hide the system X control.
I've tried everything and it didn't work
if you just want to close, without showing an messagebox, you will just need:
Private Sub FORM1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
>e.Cancel = False
>FORM2.Show() (if you want to show another form)
End Sub
Hope this helps you...!