Mark
Mark

Reputation: 25

System Object Disposed Exception

I have a form that has a few buttons, one button allows me to create multiple new forms (form2 with a textbox, the button creates a new instance of this form everytime it is clicked.)

My issue is that I keep getting the exception System.ObjectDisposedException: 'Cannot access a disposed object. Object name: 'TextDocument'.'

I am also not able to create multiple forms with my button, it creates one instance that I can save and open, but I am unable to create anymore.

I did declare a new form being made, gave it a name, etc. Which looks like this

  public partial class MainForm : Form
    {
        TextDocument Text;
        public MainForm()
        {
            InitializeComponent();
            Text = new TextDocument();
        }

In my first form(main form which is an mdi form) I have the following code for my button.

private void btnNewTool_Click(object sender, EventArgs e)
       {
           Text.MdiParent = this;
           Text.Show();
       }

In my second form below, which is called TextDocument, all I have is

 public string TextFileName
        {
            get { return tbText.Text; }
            set { tbText.Text = value; }      
        }

Which I do not think should be an issue as all I am doing is gathering text for my save button which works perfectly fine.

Overall what I am trying to do is have a button that when clicked I can create a new instance of form2 which is called Text. But I keep getting the exception System.ObjectDisposedException: 'Cannot access a disposed object.Object name: 'TextDocument'.'and I am unsure how to fix this.

(this is the first programming language I have been working on for the last 3 months, so any help is very much appreciated.).

Upvotes: 0

Views: 981

Answers (1)

LarsTech
LarsTech

Reputation: 81675

MDI means "Multiple Document Interface". You wrote your code as a Single Document Interface.

Remove these lines:

TextDocument Text;
Text = new TextDocument();

Your click event should look something like this:

private void btnNewTool_Click(object sender, EventArgs e)
{
   TextDocument td = new TextDocument();
   td.MdiParent = this;
   td.Show();
}

Upvotes: 1

Related Questions