MessageBox.Show Method in C#

Introduction

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. Something like this is below.

Example

Figure 1. Windows Form

Let's say you want to show a message on a button click event handler. Here is the code for that.

Figure 2. Code Snippet

OUTPUT

Figure 3. Showing the output

Note. By default, the OK Button will be shown.

Figure 4. Second and third argument MessageBoxIcon

Figure 5. The fourth argument specifies MessageBoxIcon

What is DialogResult?

DialogResult is an enumeration of the possible return values of a dialog box, including a MessageBox. The Show method returns a DialogResult that tells us what button a user has clicked on in the message box.

publicstaticSystem.Windows.Forms.DialogResultShow(stringtext);

Here are the values of DialogResult.

  • Abort: The dialog box return value is Abort (usually sent from a button labeled Abort).
  • Cancel: The dialog box return value is Cancel (usually sent from a button labeled Cancel).
  • Ignore: The dialog box return value is Ignore (usually sent from a button labeled Ignore).
  • No: The dialog box return value is No (usually sent from a button labeled No).
  • None: Nothing is returned from the dialog box. This means that the modal dialog continues running.
  • OK: The dialog box return value is OK (usually sent from a button labeled OK).
  • Retry: The dialog box return value is Retry (usually sent from a button labeled Retry).
  • Yes: The dialog box return value is Yes (usually sent from a button labeled Yes).

For example, if you want to ask a user to close a form on a Yes button click of a message box, you can do something like this.

Form1.cs code

private void button1_Click(object sender, EventArgs e)
{
    DialogResult result;
    result = MessageBox.Show("Welcome to C# Corner", "Learn C#", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
    
    if (result == DialogResult.Yes)
    {
        Close();
    }
}

OUTPUT

Figure 7. Final output

Thank you.

Learn more about C# MessageBox, here is a detailed article: Message Box in C#


Similar Articles