fifamaniac04
fifamaniac04

Reputation: 2383

C# create custom dialog result form

I have a two forms in C#, one I intend to use as a dialog result and the other is the "main" form. how do I set up the other form so that the code in form1 waits until the second form is dismissed before resuming executing the next line of code?

Upvotes: 2

Views: 4616

Answers (3)

Vishal Suthar
Vishal Suthar

Reputation: 17194

You can try ShowDialog method:

if (MyForm.ShowDialog(this) == DialogResult.OK)
{
    // Resume after closure on "OK"
}
else
{
    // Resume after closure on "Cancel/Abort/No/None/Etc..."
}

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

The code might look like this:

...

var o = new Form2();
o.ShowDialog();

// resumes after closure of Form2
...

The other thing you can do here is:

var res = o.ShowDialog();
if (res == DialogResult.Cancel)
{
    // do something because the user canceled the dialog
}

Further, you can set default Accept and Cancel buttons on the form. Just go to the properties of the Form and take note to the CancelButton and AcceptButton. That does two things:

  1. Determines the DialogResult sent by those buttons.
  2. Manages the Enter and Esc key strokes for those buttons.

Upvotes: 0

Maarten
Maarten

Reputation: 22945

You can use the Form.ShowDialog method on form2.

// Some code in form1
var form2 = new Form2();
form2.ShowDialog();
// Note: this code will resume after form2 has been closed.

Alternatively, you can subscribe to the Form.Closed event to run some code when form2 closes.

// Some code in form1
var form2 = new Form2();
form2.Closed += (s, e) {
    // Note: this code will run after form2 has been closed.
};
form2.Show();

Upvotes: 5

Related Questions