TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

Button click open Form 2 and close Form 1

A common case in normal windows application is to Open a new form(say Form2) while clicking a button in Form1 and close Form1 also.Read to know the different ways to achieve this.

A common case in normal windows application is to Open a new form(say Form2) while clicking a button in Form1 and close Form1 also. There are different ways you can achieve this.  

 

1)     Close Form1 and Show Form2.        

        private void btnLogin_Click(object sender, EventArgs e)
        {
            this.Close(); //Close Form1
            Form2 frm2 = new Form2();
            frm2.Show(); // Launch FOrm2
        }

 

2)  Use Application.Run for each form in Main() method.       

       //Declare a bool property.this property will be set to true on button click.    
        public bool IsLoggedIn { get; set; } 
        private void btnLogin_Click(object sender, EventArgs e)
        {
                    this.Close(); //Close Form1
           
                    //Set the property to true while closing Form1.This propert will be checked before running Form2 in Main method.
                     IsLoggedIN = true;
        }

 

 

      Update the Main() method as below.      

        [STAThread]
        static void Main()
        {
           Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 frm1 = new Form1();
            Application.Run(frm1);         
           
            //Here the property IsLoggedIn is used to ensure that Form2 won't be shown when user closes Form1 using X button or a Cancel                         //button inside Form1.
           if (frm1.IsLoggedIn)
            {
                Application.Run(new Form2());
            }
        }

 

3)    Hide Form1 and Show Form2.But Form1 will remain live as long as the application remain open.Not at all suggested. 

         private void btnLogin_Click(object sender, EventArgs e)
        {
            this.Hide(); //Hide Form1.
            Form2 frm2 = new Form2();
            frm2.Show(); // Launch Form2
        }

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading