c# close one form from another

Hi

I am using c# with windows Forms.

I have a form that accepts some information, then opens a second form. After the second form is open I want to close the first form. How do I do that?
Charles BaldoSoftware DeveloperAsked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Right...if the first form is the "startup form" then you can't close it or the app will close!

One way around this is to start the app with an instance of ApplicationContext instead of an instance of a Form.  Then the app will not die unless you explicitly tell it to with Application.Exit().

Below is the implementation in "program.cs", Form1 and Form2:
(look closely for the breaks between the files)
namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyContext());
        }
 
        private class MyContext : System.Windows.Forms.ApplicationContext
        {
 
            public MyContext()
            {
                Form1 f1 = new Form1();
                f1.Show();
            }
        }
    }
}
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.Show();
            this.Close();
        }
    }
}
 
namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
 
        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }
}

Open in new window

0
 
joechinaConnect With a Mentor Commented:
just close the form immediate after the code where you open the second form.
0
 
Charles BaldoSoftware DeveloperAuthor Commented:
I Have this

       Success frm = new Success(CompanyID);        
       frm.ShowDialog();
       this.Close();

and it closes both forms.

 
0
 
Charles BaldoSoftware DeveloperAuthor Commented:
Thanks both
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.