1

How to open a form multiple times? I have this event:

Form2 myForm = new Form2();

private void button_Click(object sender, EventArgs e)
{
   myForm.Show();
}

When I debug my project with VisualStudio 2008, the first time I clicked on the button, the Form was Showed, but when I closed it, and I tried to open it again, i get an error similar to this: Impossible to access an eliminated object. Object Name: 'Form2'.

Can anyone explain this behaviour to me?

user973511
  • 329
  • 3
  • 11
  • 1
    if you want to reopen your form you'd be better off to just hide it. –  Oct 23 '11 at 11:16

3 Answers3

5

You can also override Form2 Closing event, interrupt it and call Hide() method instead. This way, you don't have to create new instance everytime you want to show your window.

Edit:
Here's example of question on Stackoveflow explaining this method. What you'll have to do, is when creating original instance of your Form2 class, hook up to its closing event by adding following code to the Form2 class:

    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        Hide();
        e.Cancel = true; 
    }

And that's all. You don't have to change your button_Click handler.

Community
  • 1
  • 1
k.m
  • 30,794
  • 10
  • 62
  • 86
  • 1
    Why not call `Hide()` directly instead? –  Oct 23 '11 at 11:18
  • @UrbanEsc: OP never specified how he is closing `Form2` - and since there are multiple ways to do so, it's always better to handle closing at one single point. But sure, you could call `Hide()` directly - it's just more scenarios to go through. – k.m Oct 23 '11 at 11:53
2

When you closed your form it's disposed (and can't show again), you should create new instance (in your button handler event):

Form f = new Form();
f.Show();
Kamil Lach
  • 4,519
  • 2
  • 19
  • 20
1

where do you create Form2 ?

you could have a local field of your current form to hold a reference to it, something like:

private Form2 myForm2;

then when you want to show it you can do this:

if(myForm2 == null)
{
  myForm2 = new Form2();
}

myForm2.Show();

put the second snippet in the Button_Click event and the first one on the Form1 class outside from any method. It should work then.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • I created Form2 on the Form1 class outside from any method, and I put the second snippet in the Button_Click event, but It doesn't work... I have the same error... – user973511 Oct 23 '11 at 10:25