Bjornen
Bjornen

Reputation: 89

Form.Show(): Cannot access a disposed object

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.

Upvotes: 6

Views: 24216

Answers (4)

Sibtain
Sibtain

Reputation: 108

Wile Implementing singleton pattern on windows form I got this error too. The solution is that you have to assign a null value to the static reference in

protected override void Dispose(bool disposing)

by putting simple line.

obj=null;  //obj is the static reference in the class.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460028

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();

Upvotes: 6

Bjornen
Bjornen

Reputation: 89

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...

Upvotes: 2

CodeTherapist
CodeTherapist

Reputation: 2806

The problem is that your form object loose the scope and is disposed off. If you want to keep the dialog open, use Form.ShowDialog();

Try this:

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

Upvotes: 1

Related Questions