C# Tutorial - MessageBox


A MessageBox can be used to display a message to the user. Although it is a class in and of itself, you cannot create a new instance of the class. Instead, to display a message, you call the static method MessageBox.Show. The title, message, buttons, and icons displayed in the message box are determined by parameters that you pass to this method. This can be shown using some simple examples.

A Simple Message

In our application, we simply pass the method a message to display as a String.

MessageBox.Show(String message)

A Message and a Caption

We could change our message box, so that the title also displays something. This is done by passing a second string into the method as a caption.

MessageBox.Show(string message, string caption)

A Message, Caption and Buttons

We can change the buttons that appear on the message box by adding a third parameter to the method. This parameter is one of the MessageBoxButtons enumeration values that specifies which buttons to display in the message box.

AbortRetryIgnore - The message box contains Abort, Retry, and Ignore buttons.

OK - The message box contains an OK button. (This is the default setting giving us a message box that is the same as in our original application.

OKCancel - The message box contains OK and Cancel buttons.

RetryCancel - The message box contains Retry and Cancel buttons.

YesNo - The message box contains Yes and No buttons.

YesNoCancel - The message box contains Yes, No, and Cancel buttons.

A Message, Caption, Buttons and Icons

An icon can also be added to a message box. This is achieved by passing in a fourth parameter to the method. This parameter is one of the MessageBoxIcon enumeration values that specifies which icon to display in the message box.

Asterisk or Information - The message box contains a symbol consisting of a lowercase letter i in a circle.

Error, Hand or Stop - The message box contains a symbol consisting of white X in a circle with a red background.

Exclamation or Warning - The message box contains a symbol consisting of an exclamation point in a triangle with a yellow background.

Question - The message box contains a symbol consisting of a question mark in a circle.

Other Variants

The MessageBox.Show method has many more variations involving the parameters that you can specify. For a full list visit MSDN at http://msdn2.microsoft.com/en-us/library/system.windows.forms.messagebox.show.aspx


<< Previous Contents Next >>

© Publicjoe, 2008