How would I say if the yes button on the messagebox was pressed do this,that and the other? In C#.
The first button on the message box is the default button. The second button on the message box is the default button.
MessageBox is a class in C# and Show is a method that displays a message in a small window in the center of the Form. MessageBox is used to provide confirmations of a task being done or to provide warnings before a task is done. Create a Windows Forms app in Visual Studio and add a button on it.
Displays a modal dialog box that contains a system icon, a set of buttons, and a brief application-specific message, such as status or error information. The message box returns an integer value that indicates which button the user clicked.
Your call to MessageBox.Show
needs to pass MessageBoxButtons.YesNo
to get the Yes/No buttons instead of the OK button.
Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes
....
if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { // user clicked yes } else { // user clicked no }
If you actually want Yes and No buttons (and assuming WinForms):
void button_Click(object sender, EventArgs e) { var message = "Yes or No?"; var title = "Hey!"; var result = MessageBox.Show( message, // the message to show title, // the title for the dialog box MessageBoxButtons.YesNo, // show two buttons: Yes and No MessageBoxIcon.Question); // show a question mark icon // the following can be handled as if/else statements as well switch (result) { case DialogResult.Yes: // Yes button pressed MessageBox.Show("You pressed Yes!"); break; case DialogResult.No: // No button pressed MessageBox.Show("You pressed No!"); break; default: // Neither Yes nor No pressed (just in case) MessageBox.Show("What did you press?"); break; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With