A Message Box Example
Explanation of using a message box.
A Message Box Example
Explanation of using a message box.
Message Boxes
A message box is similar to an input box. The message box can be used as either a function (returns an answer) or a statement (no answer returned) The programmer can select the type of message box to display. The type indicates which command buttons to display: Yes, No, OK, Cancel, Abort, Retry, etc.
There are several formats for opening a message box:
The simplest format for the statement is
MessageBox.Show("Message");
You can also include the caption:
MessageBox.Show("Message", "Caption");
Example:
private void btnRed_Click(object sender, EventArgs e)
{
MessageBox.Show("Turn the form red!","RED");
BackColor = Color.Red;
}
These two methods are usually used when the only button on the message box is OK.
We do not need to find out which button they pressed, they’re going to press OK!
As soon as the user presses OK, the message box disappears and the form turns red.
In the next example the user is given a choice. Since we do not know which button they will press, we will store the result so we can look at the answer.
We will turn the form red only if the press Yes.
Type the code for a button as shown below to display this message box:
:
Notice that as you type the code most of the choices are selected from pop-up boxes.
private void btnRed_Click(object sender, EventArgs e)
{
DialogResult result;
result =MessageBox.Show("Do you like red?","RED",MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
BackColor = Color.Red;
}
}
Experiment: Once the user presses yes, the button does not have any affect. If they click No change the backcolor to some other color.