0

I'm using code from this example: Messagebox with input field

Once the user clicks the button on the form, nothing happens. The form remains. Do I need to wireup something for the modal to go away so I can get the textbox result?

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}
Community
  • 1
  • 1
4thSpace
  • 43,672
  • 97
  • 296
  • 475

1 Answers1

2

To get the form to close, you'll need to call Close(); within the button clicked event on Form2.

Dave
  • 897
  • 8
  • 8
  • I added that to the button click event. However, I don't fall into the conditional and never capture the textbox value. – 4thSpace Jun 15 '16 at 20:23
  • 1
    Make sure the button clicked event also sets DialogResult = DialogResult.OK; – Dave Jun 15 '16 at 20:25
  • Alternatively, you could set the `DialogResult` property of the `Button` itself in the winforms designer for `Form2`. – wablab Jun 15 '16 at 20:27
  • @wablab: That's the way to go. Closes the form and everything. Do they really need to call .Dispose() in the example? – 4thSpace Jun 15 '16 at 20:57
  • If this applies to you, you should call dispose. (or wrap the form in a using) : The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection. – Dave Jun 15 '16 at 21:05
  • Since the scope of the `testDialog` variable is within the `ShowMyDialog` method, and since it's initialized with a `new Form2()` on every call to `ShowMyDialog`, I think it's a good idea to go ahead and call `testDialog.Dispose()` at the end of the method. Also, what @Dave said. :) – wablab Jun 15 '16 at 21:06