1

Here's my code

Form1

TicketDetails td = new TicketDetails(getTicketID());
td.Show();

I want to close Form1 when td is shown.

Taryn
  • 242,637
  • 56
  • 362
  • 405
Cocoa Dev
  • 9,361
  • 31
  • 109
  • 177

4 Answers4

4

If Form1 is the form you passed as an argument to Application.Run then you cannot close it, or your application will exit. What you can do though is hide the form when td is displayed.

TicketDetails td = new TicketDetails(getTicketID());
td.Show();

// Hide the main form
form1.Hide();

If Form1 is not your application's main form, then you may simply call Close() on form1.

Edit @comment,

public class Form1 : Form
{
    private override OnLoad(object sender, EventArgs e) {
        DoWork();
    }

    public void DoWork() {
        // your code
    }
}

Then a for-instance.

TicketDetails td = new TicketDetails(getTicketID());
td.Show();

form1.Hide();

// example, maybe you need to call your work method
form1.DoWork();
David Anderson
  • 13,558
  • 5
  • 50
  • 76
  • The form is not my main one but the user can open it again and I need the Load method to be called – Cocoa Dev May 02 '12 at 16:26
  • Make a new public method in your Form1 class that needs to do the work, and you can call that method from both your OnLoad, and from other forms. – David Anderson May 02 '12 at 16:29
3

If you want to close the first form after the second has been displayed use the Form.Shown event:

td.Shown += (o, e) => { this.Close(); }
td.Show();

For other events that might be interesting, check out order of events in Windows Forms. And of course it might also be OK to close the current form immediately:

this.Close();
td.Show();
Jon
  • 428,835
  • 81
  • 738
  • 806
  • do I add the td.shown += (o,e) to the TicketDetails_shown or Form1_shown? – Cocoa Dev May 02 '12 at 16:29
  • @CocoaDev: Added another line of code to clarify. There are lots of places where it will work, but IMHO it's best to do it just before `td.Show()`. – Jon May 02 '12 at 16:31
  • Closing the parent will not work. [This](http://stackoverflow.com/a/13459878/2102094) SO answer works, only slightly different from this solution. – ram Mar 22 '17 at 05:24
1

I've done something like this:

TicketDetails td = new TicketDetails(getTicketID());
td.Show();
this.Hide();
td.Close += (object sender, EventArgs e) =>
{
    td.Parent.Close();
};
Joe
  • 80,724
  • 18
  • 127
  • 145
0

As long as TicketDetails isn't modal then any code after td.show() will run.

I'm also assuming that Form1 is the startup form for your project. If that's the case then using .close will stop your app.

have you tried this:

TicketDetails td = new TicketDetails(getTicketID());
td.Show();
Form1.Hide();

This obviously hides Form1

Thanks

Paul

PaulG
  • 592
  • 2
  • 8
  • Sorry if the answer is the same as above, I had to answer the phone in the middle of writing it :) – PaulG May 02 '12 at 16:21