I want to make a MessageBox confirmation. Here is the message box:
MessageBox.Show(\"Do you want to save changes?\", \"Confirmation\", messageBoxButtons.YesNoCan
This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:
//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
...
}
Hope it helps
DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{
//...
}
else if (result == DialogResult.No)
{
//...
}
else
{
//...
}
You can also do it in one row:
if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)
And if you want to show a messagebox on top:
if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)
Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.
var result = MessageBox.Show(@"Do you want to save the changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
switch (result)
{
case DialogResult.Yes:
SaveChanges();
break;
case DialogResult.No:
Rollback();
break;
default:
break;
}
If you're using WPF and the previous answers don't help, you can retrieve the result using:
var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
// Do something
}