Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form.Show(): Cannot access a disposed object

Tags:

c#

winforms

I have been stuck with this for some time now. I can't open a new form on button click. If i create and .Show() form in the start form constructor i will work. I dont get it! :-(

StartUp Form

public Form1()
    {
        InitializeComponent();
        startmessage();
        br = Logic.loadXML("theshiiiiiittt.xml");
        br2 = br.Clone();
        loadboxes();
        //serializeTest();
        t = new Thread(contactDBUpdate);
        //t.IsBackground = true;
        t.Start();

    }

Button event:

private void resultButton_Click(object sender, EventArgs e)
    {
        ResultForm rf = new ResultForm(this);
        rf.Show();
        this.Enabled = false;
    }

Hope this is enough.

like image 852
Bjornen Avatar asked Jan 10 '14 10:01

Bjornen


2 Answers

In my case it was caused by the fact that i wanted to make my forms non-modal. So i changed them from form.ShowDialog(parentForm) to form.Show().

But that caused the ObjectDisposedException if i try to show a form a second time because somewhere in the code was this.Close();. Form.Close also disposes it.

MSDN:

When a form is closed, all resources created within the object are closed and the form is disposed.

I just needed to change

this.Close();

to

this.Hide();
like image 176
Tim Schmelter Avatar answered Sep 18 '22 04:09

Tim Schmelter


Found my code problem. I took one more look at the Stack trace and found i a message "Icon".

           this.Icon.Dispose();

Startupform had this line.

This code fixed my problem:

private void resultButton_Click(object sender, EventArgs e)
{

    ResultForm rf = new ResultForm(this);
    rf.Icon = this.Icon;
    rf.Show();
    this.Enabled = false;
}

Thanks for the helping hands...

like image 38
Bjornen Avatar answered Sep 18 '22 04:09

Bjornen