Click here to Skip to main content
15,895,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I am developing a windows application using c#. I have one form open and on button click of form 1, I am opening form 2, i.e. both Forms form 1 and form 2 are opened. Form2 Show in task-bar property is set to false. I want to close or hide the form 2 on button click event of form 1. I tried to use Hide and Close Method, but the form 2 is still displayed.
Any Help !!!

Thanks In Advance !!!

C#
bool Display; // declared at class level. 
//btnshow_hide is on form 1.
private void btnshow_hide_Click(object sender, EventArgs e)
        {
            form2 tc = new form2();
            if (Display == true)
            {
                Display = false;                
                tc.Show();
            }
            else if (Display == false)
            {
                Display = true;
                tc.Hide();
                //tc.Close();
            }
        }
Posted
Updated 29-Dec-12 1:37am
v2
Comments
Jibesh 29-Dec-12 7:24am    
Can you copy the code you did. Solution provided by OriginalGriff should resolve the issue
Ank_ush 29-Dec-12 7:38am    
Copied the code, you can review....

1 solution

You have to use the Hide or Close method of the form on the actual instance of the form, not on a new one:

C#
private Form2 form2;
private void OpenForm2()
   {
   if (form2 == null)
      {
      form2 = new Form2();
      }
   form2.Show();
   }
private void CloseForm2()
   {
   if (form2 != null)
      {
      form2.Close();
      form2 = null;
      }
   }




"Its not working. I have button on form 1, I want to use the same button to show and hide the form 2."

Not exactly a big change:
C#
private Form2 form2;
private void ToggleForm2()
   {
   if (form2 == null)
      {
      form2 = new Form2();
      form2.Show();
      }
   else
      {
      form2.Close();
      form2 = null;
      }
   }
 
Share this answer
 
v2
Comments
Ank_ush 29-Dec-12 7:00am    
Its not working. I have button on form 1, I want to use the same button to show and hide the form 2.
Ank_ush 29-Dec-12 7:39am    
Review my code....
OriginalGriff 29-Dec-12 7:49am    
Yes. Now look at mine. Do you see the difference? That is why my code works, and yours doesn't...

If you don't see the difference, it is that I keep a copy of the reference to teh form I open, so I can close it again. You don't.
Ank_ush 29-Dec-12 8:03am    
Yes Friend, i changed the code and it worked... Thanks............
OriginalGriff 29-Dec-12 8:15am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900