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));
            if(confirm==6)
            {
                Application.Exit();
            }
            [B]else
            if(confirm==7)
            {
                //e.Cancel;
                return;
            }[/B]
        }

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...

Recommended Answers

All 3 Replies

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);
}

thanks to all but I've already coded it and its simply working great.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.