Hi all,

I've a code in vb.net 2003 which prompts user while he/she tries to close the form by clicking the form's close button('X'). If answer is yes the form closes but if the answer is no it stays. Now I want to write the similar code in a C# form also. I've already coded it. It's also working but the problem is when I'm trying to not to close the form by clicking on the 'NO' button in the messagebox the form still closes itself. Here is the code fragment what I wrote :-

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
            int confirm;

            confirm=System.Convert.ToInt32(MessageBox.Show("Sure to exit ?","Confirm Exit",MessageBoxButtons.YesNo,MessageBoxIcon.Question));

The bolded part is where I'm getting the problem. Plz help me to figure this out. I'm a beginner in C#. So, if anybody can help me plz do so. Thanks in advance...

Edited by happygeek: fixed formatting

10 Years
Discussion Span
Last Post by choudhuryshouvi

probably wont fix it, but if you're using a messagebox and getting the result from it, you should use the DialogResult property. It would be something like this...

DialogResult dr;
dr = MessageBox.Show("Yes or No?", "Prompt", MessageBox.Buttons.YESNO, MessageBox.Icon.Question);

Then check for dr == DialogResult.Yes or dr == DialogResult.No


This works in VS2005, and should work in 2003

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
e.Cancel = (e.CloseReason == CloseReason.UserClosing && MessageBox.Show("Are you Sure ?", "Close", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.