Click here to Skip to main content
15,894,955 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose I have two forms(Form1,Form2)
in form 1 I have a button

C#
namespace sample_form
{
    public partial class Form1 : Form
    {
        Form2 f = new Form2();
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            f.Show();
        }
    }
}

in form 2 I have a textbox;

I want to show/close form2 in button1_click(in form1)
it says object disposed !,for this in form2 I wrote
C#
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }



but if user open the form2 and write somthing in textbox and close it,then open form2 by the button , the text he wrote remains in textbox (because I just hide it),how can I instance a new one from Form2 without the error:disposed ?! :((
Posted

Why do u hide it? What for?
Just create new instance of your form.

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


Also, as I understand, the garbage collector will dispose your form in some time, and f.Show will throw an exception. So, create instance every time.
 
Share this answer
 
If you absolutely need to reuse the same form instance, then write a Clear method that restores the UI to the default state before re-showing it.

Or if that's not a requirement, instantiate a new form instance each time you want to show it (as neosRu suggested above).
 
Share this answer
 
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }


This code appears to be in form2 rather than form 1. This is creating the error. You need to place this code in form1 and set form2 to null from there.
 
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