1
votes

This question will definitely seem redundant but I've tried seemingly everything!

Ok I have form1 and form 2. I want to open form2 from buttonclick on form1 and have form1 close.

I've tried the:

Form2 newform = new Form2();
this.Close();
newform.Show();

I've tried moving the second line in all possible places inside the buttonclick function. But my problem is that if I use the "this.Close();" command it closes both forms, if I use the "this.Hide();" command it leaves the process open and I have to manually close it to debug again.

The(this.Close();" works on any other form (ex. form2 close => open form3 ETC)

Does anyone know any other way to have it close it but not close the entire application?

2
can you use two form and apply runat=server?Ranjita Das
@RanjitaDas this makes absolutely no sense at all.Pierre-Luc Pineault

2 Answers

2
votes

I tried to use ApplicationContext in Program.cs.

Take a look at the below code. Form1 and Form2 both contain a Button.

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main ()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MyApplicationContext context = new MyApplicationContext();
        Application.Run(context);
    }

    public class MyApplicationContext : ApplicationContext
    {
        private Form1 form1 = new Form1();

        public MyApplicationContext ()
        {
            form1 = new Form1();
            form1.Show();
        }
    }
}

Below is the code for Form1

    private void frm1Button1_Click (object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.Show();
        this.Close();
    }

And here is for Form2.

    private void frm2Button1_Click (object sender, EventArgs e)
    {
        Form1 frm1 = new Form1();
        frm1.Show();
        this.Close();
    }
0
votes

The problem you are facing is that you cannot close the main form of an application (without closing the whole app). you need to rethink how your app is organized and maybe hide the main form while the other one is on the screen or something similar.