Trapping Closing event when a user clicks on the close (red "X" on frame)

R

RSH

I am trying to figure out how I can trap the Closing Event that occurs when
a user attempts to close the window by clicking on the red"X".

I tried this code which I found online but nothing happens.

What do I need to do to trap and give the ability to save changes before the
window closes?

Thanks,
Ron



private void frmDataEditGrid_Closing(object sender, CancelEventArgs e)

{

e.Cancel = true;

if (MessageBox.Show("Do you want to save changes to your text?", "My
Application",

MessageBoxButtons.YesNo) == DialogResult.Yes)

{


e.Cancel = true;


}

}
 
M

Marc Gravell

The code as posted won't work, no (it always stops the close, as e.Cancel is
always set to true), but the Closing event is fine;

The following, added to a form, works for me:

public Form1() { // ctor
// initialise and hook up the closing event (event could also be
attached in the IDE / InitializeComponent, but I like it here...)
InitializeComponent();
FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}

void Form1_FormClosing(object sender, FormClosingEventArgs e) { //
event handler
bool cancel = false; // let the form close by default
if(MessageBox.Show("Cancel?","Test",MessageBoxButtons.YesNo)==DialogResult.Yes)
{
cancel = true; // don't close...
}
e.Cancel = cancel;
}

Marc
 
J

Joanna Carter [TeamB]

"Marc Gravell" <[email protected]> a écrit dans le message de (e-mail address removed)...

Simplified to :

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = MessageBox.Show("Cancel?","Test",MessageBoxButtons.YesNo) ==
DialogResult.Yes)
}

Joanna
 
G

Guest

Two quick things... when you say that nothing is happening... I am guessing
you are not even seeing the message box. If that is the case, you need to add
a bit of code to have your function be called when the event is raised.

The easiest way to do that would be to view your form in the form designer,
and in the Properties window click the Events button (has the lightning bolt
icon, and locate the Closing event. Finally, use the drop down to select your
handler, frmDataEditGrid_Closing.

Second, remove the first instance of ‘e.Cancel = true’ which is being called
no matter what. Without it, the option you choose from the prompt will cause
the form to close or not.

Brendan
 
R

RSH

Thanks alot. I am just starting to understanding wiring events...this was
very helpful. THANKS!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top