-3

I have a piece of code that throws an exception and error after running for a second time. Here it is:

static Form Window = new Form();
static public void Configuration()
{ 
    Window.Height = 800;
    Window.Width = 800;
    Window.Text = "Homework";

    Window.Paint += Window_Paint;

    Window.Show();
}

This code is inside a class and it throws an exception at "Window.Show();" saying that it:

ObjectDisposedException: Cannot access a disposed object.
Object name: 'Form'.

Please suggest a way that I can fix this so that it doesn't happen again.

A Zhitom
  • 9
  • 4
  • 7
    " a way to fix this so that it doesn't happen again": don't use static `Form` object. create a new instance when necessary – ASh Jul 08 '17 at 12:15

1 Answers1

0

The code you probably want to use is:

static public void Configuration()
{ 
    var window = new Form();

    window.Height = 800;
    window.Width = 800;
    window.Text = "Homework";

    window.Paint += Window_Paint;

    window.Show();
}

This will ensure that a new instance of Form is created every time that Configuration is called.

mjwills
  • 23,389
  • 6
  • 40
  • 63