For .NET developers, the MessageBox can be a very handy way to display a short message to users, but it's also a great way to gather user input. Using the MessageBox in this way helps your application blend into the Windows look and feel and ensures that your application will behave in a way that is familiar to users. Zach Smith shows you how to use C#, the .NET Framework, and the MessageBox as a user input component by using the DialogResult object.
This blog post is also available in PDF in a TechRepublic download.
Simple exampleThe code in Figure A shows a very simple use of the MessageBox. Here, we are just displaying text to the user:
Displaying textThis code will show a popup similar to Figure B.
As you can see, this is a simple popup with only one button — OK.
Using the DialogResult object
Even though it is not used in the above example, a DialogResult object (it is actually an enum) is always passed back from the MessageBox.Show method. By examining this object, we can determine which buttons on the dialog the user clicked. This becomes important once we start popping up Yes/No dialogs.
Within the DialogResult enum are values that correspond to the various buttons you can place on a dialog. The following values are in the DialogResult object:
Before you will get any use out of the DialogResult object, you will need to know how to instruct the MessageBox.Show method to place the buttons you specify on the dialog. This is a simple matter of using one of the overloads on the Show() method.
The overload we'll use in our examples has a signature of the following:
Show(string text, string caption, MessageBoxButtons buttons);
The MessageBoxButtons object is what we're interested in here. This enum allows you to specify which buttons you'd like displayed on the dialog. The following are valid values for the MessageBoxButtons enum:
These are pretty self-explanatory — each word in the enum value will be a button on the dialog. So OKCancel will have two buttons — OK and Cancel. YesNoCancel will have three buttons — Yes, No, and Cancel.The code in Figure C puts both the MessageBoxButtons enum and the DialogResult enum to work to display a dialog with Yes and No buttons:
Yes and No buttonsThis code will display a dialog similar to the one shown Figure D.
Yes or No dialog
The code then goes on to run logic on the DialogResult value that was returned from the MessageBox.Show() method.Showing an Abort, Retry, Ignore dialog is just as simple. The code in Figure E shows how to do this.
Abort, Retry, Ignore codeThis shows a dialog similar to the one shown in Figure F.
Abort, Retry, Ignore dialog
The other types of dialogs available from the MessageBox class are used in the same manner; you simply test for whatever values correspond to the MessageBoxButtons value you supplied and take appropriate action based on the input.