Free Information Technology Magazines and eBooks

Wednesday, January 06, 2010

Add Confirmation Dialog Box When Closing a VB.NET form

To prevent your user from accidentally closing a form, you can add a confirm dialog that will ask first if the user indeed want to close the active form or cancel it instead. With this form behavior you can prevent losing unsaved work. In VB.NET, you can trap closing of form on FormClosing attribute. FormClosing event occurs whenever the user closes the form and before the form has been closed. Any code written on this block is executed first before the program close the active window.

Add Confirmation Dialog box When Closing a VB.NET form

To ask for confirmation, copy and paste the following code inside the FormClosing event:

If MessageBox.Show("This will close this form. Continue?", "Confirm Closing", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then
e.Cancel = True
End If


The MessageBox will provide user the option to continue closing by clicking the "Yes" button or cancel it by hitting the "No" button. If user presses the "No" button, VB will assign true to the Cancel property of the "e" argument variable that will abort the closing of the form.

For More Coding Tips & Tricks, subscribe now.

7 comments:

John Ortiz said...

Hi! I need the equivalent snippet for WPF. Thanks anyway for this info.

Anonymous said...

pressing No still terminates the program =(

Anonymous said...

Your code works... but... I also have some "hit ESC to close" in my Form1_KeyPress event.

Why does it ask TWICE when I hit ESC to try to close?

::Sebaik-baik kehidupan:: said...

the code works! thanks..
how to do this:

when user click close, if the form has been edited, user will be prompt either to save data, dont save + close or cancel..

but if user click close, and then the form is not edited, user will only be prompted either to continue or cancel..

thank you..

amigos said...

hey its showing error on e.cancel "cancel cannot be member of system.event.args" how to resolve it help me

Anonymous said...

Nice! thanks for the code
It works

Anonymous said...

Nice! thanks for the code
IT Works