Search code examples
c#winformsbuttonobjectdisposedexception

C# open forms with button


I want to ask this. I have a form this form can control 4 more forms. When i click on the "open form 1" button it is okay but when i clicked "open form 2 " i getting some problem.

my codes like

public Form1()
    {
        InitializeComponent();
    }

    Form2 ac = new Form2();
    Form3 ac2 = new Form3();


    private void button1_Click(object sender, EventArgs e)
    {
        ac2.Close();

        ac.Show();

    }

    private void button2_Click(object sender, EventArgs e)
    {
        ac.Close();

        ac2.Show();

    }

error tag = System.ObjectDisposedException (BUTTON 1 CLICK AFTER BUTTON 2 CLICK)


Solution

  • When you Close a form, the form object gets disposed and hence you wouldn't be able to call Show on the disposed object. Read about Form.Close() here.

    When a form is closed, all resources created within the object are closed and the form is disposed. You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler. If the form you are closing is the startup form of your application, your application ends.

    You should be using Hide method instead of Close on clicking the buttons, which will only hide the form from the user. Modify your functions as follows:

    private void button1_Click(object sender, EventArgs e)
    {
        ac2.Hide();
    
        ac.Show();
    
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        ac.Hide();
    
        ac2.Show();
    
    }
    

    OR

    Create new instance of form on button click handlers as follows:

    private void button1_Click(object sender, EventArgs e)
    {
        ac2.Close();
        ac2 = null;
    
        if(ac == null)
        {
           ac = new Form2();
        }
    
        ac.Show();
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        ac.Close();
        ac = null;
    
        if(ac2 == null)
        {
           ac2 = new Form3();
        }
    
        ac2.Show();
    }