C# Tutorial - DialogResult


At this point it is worth looking at the DialogResult property of the windows Form class.

When a Form is used as a modal dialog box, buttons can be used to set the value of the DialogResult property so that the result is available to the calling Form. Using the MessageBox class is an excellent way of understanding this.

Modify the button1_Click method to the following code:

private void button1_Click(object sender, EventArgs e)
{
  DialogResult result = MessageBox.Show("Would You like to close the
  parent window?", "Hey You", MessageBoxButtons.YesNoCancel);

  if (result == System.Windows.Forms.DialogResult.Yes)
  {
    this.Close(); // Closes the parent form.
  }
}

What we have done is to create an instance of the DialogResult enumeration called result. When the user presses one of the three buttons, the return type of the Show method is stored in the result variable. We can then test against the result in order to do something dependent upon it. In this case, we close the parent form.


<< Previous Contents Next >>

© Publicjoe, 2008