2

I'm trying to get the user to confirm if they want to delete a product using a MessageBox and catching its result. This is my code:

// Confirm if the user really wants to delete the product
DialogResult result = MessageBox.Show("Do you really want to delete the product \"" + productName + "\"?", "Confirm product deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.OK)
{
    MessageBox.Show("deleted");
}

When I run the code and try to delete a product, deleted never shows. On the MSDN page it says to use MessageBoxResult rather than DialogResult but Visual Studio doesn't recognise MessageBoxResult, and I use DialogResult elsewhere in my code for an open file dialog. Obviously, that's not the proper way to check it.

James Dawson
  • 5,309
  • 20
  • 72
  • 126

4 Answers4

6

You must ask for DialogResult.Yes

// Confirm if the user really wants to delete the product
DialogResult result = MessageBox.Show("Do you really want to delete the product \"" +     productName + "\"?", "Confirm product deletion", MessageBoxButtons.YesNo,  MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
    MessageBox.Show("deleted");
} 
Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
1

You have the message box type set to yes/no, yet you are trying to catch an OK result. Catch the yes and you will be sorted.

TomP89
  • 1,420
  • 3
  • 11
  • 29
0

You are using the YesNo buttons, so the DialogResult.OK has nothing to do with it. You should do

if (result == DialogResult.Yes)

for your condition.

SimpleVar
  • 14,044
  • 4
  • 38
  • 60
0

Just ask for the right DialogResult.

if (result == DialogResult.Yes)

Bear in mind, that a dialog can have different kind of results, and that you are also able to write your own results. Therefore: Have always a look on the result you are expecting and on the result you are checking.

Greetings,

Mario Fraiß
  • 1,095
  • 7
  • 15