Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
this code wil show form2 but what i want is , when i click in listbox "close form 2"
the form 2 will not close !

C#
private void button1_Click(object sender, EventArgs e)
{
Form2 myForm;
myForm = new Form2();
myForm.Show();
}


C#
private void listBox5_Click_1(object sender, EventArgs e)
{
                   if (listBox5.Text == ("close form 2"))
                     {
                         


                         Form2 myForm;
                         myForm = new Form2();
                         myForm.close();// but its not close it D:
}
}
Posted
Comments
Sergey Alexandrovich Kryukov 13-Feb-12 12:10pm    
The question shows such a big ignorance, that it may require starting to learn programming from the very beginning. Either start it now, not wasting a minute, or give up.

Good luck.
--SA

You should read a book on OO development. This code does what you ask. button1 creates a form and shows it. listbox5 creates a new form, and closes that ( only it never opened ). I also think that .close will not compile, it's .Close. But, either way, you need to keep a reference to the Form2 instance you create and close THAT, not a random new instance that has nothing to do with the form you want to close.
 
Share this answer
 
You can't close it like that - you have to close the instance of Form2 that is actually showing.
Try this:
C#
private Form2 myForm;
private void button1_Click(object sender, EventArgs e)
   {
   myForm = new Form2();
   myForm.Show();  
   }

private void listBox5_Click_1(object sender, EventArgs e)
   {
   if (listBox5.Text == ("close form 2"))
      {
      myForm.Close();
      }
   }
 
Share this answer
 
v2
Comments
fjdiewornncalwe 13-Feb-12 12:40pm    
Of course. +5.
Shahin Khorshidnia 13-Feb-12 12:58pm    
+5
You're declaring a new form in the listBox5_Click method, so it's not the same form as the one initially created.

You need to create Form2 as a variable (e.g. myForm) that can be accessed throughout your base class

so under button1_click you only need to show the form
myform.Show();

and under listBox5_Click it would be
myform.Close();

You would obviously have to instantiate your form first somewhere else (instructor perhaps)
 
Share this answer
 

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