I want to make simple Yes/No choiced MessageBox, but I think it is nonsense to design a form for that. I thought I could use MessageBox, add buttons, etc. to accomplish this. It is simple, but since there is no DialogResult returned, how do I retrieve the result?
This should do it:
DialogResult dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
//do something
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
DialogResult dr = MessageBox.Show("Are you happy now?",
"Mood Test", MessageBoxButtons.YesNo);
switch(dr)
{
case DialogResult.Yes:
break;
case DialogResult.No:
break;
}
MessageBox class is what you are looking for.
MessageBox.Show(title, text, messageboxbuttons.yes/no)
This returns a DialogResult which you can check.
For example,
if(MessageBox.Show("","",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//do something
}
The MessageBox does produce a DialogResults
DialogResult r = MessageBox.Show("Some question here");
You can also specify the buttons easily enough. More documentation can be found at http://msdn.microsoft.com/en-us/library/ba2a6d06.aspx
Use:
MessageBoxResult m = MessageBox.Show("The file will be saved here.", "File Save", MessageBoxButton.OKCancel);
if(m == m.Yes)
{
// Do something
}
else if (m == m.No)
{
// Do something else
}
MessageBoxResult is used on Windows Phone instead of DialogResult...
You can also use this variant with text strings, here's the complete changed code (Code from Mikael), tested in C# 2012:
// Variable
string MessageBoxTitle = "Some Title";
string MessageBoxContent = "Sure";
DialogResult dialogResult = MessageBox.Show(MessageBoxContent, MessageBoxTitle, MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
//do something
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
You can after
.YesNo
insert a message icon
, MessageBoxIcon.Question
@Mikael Svenson's answer is correct. I just wanted to add a small addition to it:
The Messagebox icon can also be included has an additional property like below:
DialogResult dialogResult = MessageBox.Show("Sure", "Please Confirm Your Action", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
dynamic MsgResult = this.ShowMessageBox("Do you want to cancel all pending changes ?", "Cancel Changes", MessageBoxOption.YesNo);
if (MsgResult == System.Windows.MessageBoxResult.Yes)
{
enter code here
}
else
{
enter code here
}
Check more detail from here
This simple code worked for me. I grabbed it from MSDN here:
if (System.Windows.Forms.MessageBox.Show
("Are you sure you want to add the audit?", "Add",
System.Windows.Forms.MessageBoxButtons.YesNo,
System.Windows.Forms.MessageBoxIcon.Question)
==System.Windows.Forms.DialogResult.Yes)
// Do stuff after 'YES is clicked'
else
// DO stuff after 'NO is clicked'
来源:https://stackoverflow.com/questions/3036829/how-do-i-create-a-message-box-with-yes-no-choices-and-a-dialogresult