How do I return yes or no from a message box that I made?
I made a message box, a form that has a label for a message and a label for the title.
And an OK button (do nothing).
I can rise this message box f开发者_运维问答rom any form in my program.
I need a message box that has a Yes button and No button, and to know if it pressed Yes or No, how do I do it?
What would sample code for this be?
From MSDN MessageBox.Show(...):
// Initializes the variables to pass to the MessageBox.Show method.
string message = "You did not enter a server name. Cancel this operation?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
In your button's click event handler use
this.DialogResult = System.Windows.Forms.DialogResult.Yes;
instead of
this.Close();
And then handle it as normal in your calling code.
Use:
dialogResult dr;
dr = MessageBox.show("Do you want to save the record", "Confirm", MessageBoxButtons.YesNo);
if (dr == DialogResult.yes)
{
//Code for inserting the data into the database
messageBox.show("Record saved successfully");
}
This code is for if you want to save the form data to the database after confirmation. Here I only show how to access the value of a message box where the user presses which button.
If you want to return different kinds of results (like, say, a string of text) you can do something like this:
public class MyMessageBox : Form
{
// You can add parameters here if needed
public static string Ask()
{
var form = new MyMessageBox();
form.ShowDialog();
return form.ResponseTextBox.Text;
}
// regular stuff
}
Then just do
string answer = MyMessageBox.Ask();
If running on Windows Vista or later, you can use the Windows API Code Pack to use the new TaskDialog.
MessageBox.Show
has the following method signature:
public static DialogResult Show(
string text,
string caption,
MessageBoxButtons buttons
)
Which means you can specify what buttons you would like to display.
Example
var dialogResult = MessageBox.Show("Do you have socks?", "Question.", MessageBoxButtons.YesNo);
These are the following MessageBoxButtons you can select from:
- OK
- OKCancel
- AbortRetryIgnore
- YesNoCancel
- YesNo
- RetryCancel
There is a built-in function to do this:
var result = MessageBox.Show("your message here", "title", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes) {
// ..
}
If you want to do similar, but with your own custom form, just set the "Yes" button's DialogResult
to Yes
and the "No" button's to No
, and then call ShowDialog()
on your form.
精彩评论