2

I want to show a Form called TTT so I tried this:

public static TTT ttt_local = new TTT();

private void button1_Click(object sender, EventArgs e)
{
    ttt_local.Show();
}

Then I want to close the Form from inside so ttt_local closes itself when a button in ttt_local is pressed. That works but if I want to reopen ttt_local I get an ObjectDisposedException. Can someone help me please?

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
Simon B
  • 179
  • 1
  • 1
  • 9
  • `ttt_local.Dispose();` – Raktim Biswas Aug 30 '16 at 06:27
  • Show how you close the form. I guess you need is **hide** the form instead of **closing** it. – MakePeaceGreatAgain Aug 30 '16 at 06:38
  • Never write code like this, a Form object is single-use. Once it is closed then it is no longer usable. And trying to use it again produces ODE. Create the object when you need it. If you want to enforce single-instance behavior then subscribe the FormClosed event to set the ttt_local variable back to null. – Hans Passant Aug 30 '16 at 08:17
  • Possible duplicate of [c# open a new form then close the current form?](https://stackoverflow.com/questions/5548746/c-sharp-open-a-new-form-then-close-the-current-form) – Feras Al Sous Jul 23 '18 at 10:00

4 Answers4

1

You should not need to let a form close itself, however you can set its visibility or simply hide it (the same also applies for showing a form):

Consumer-code:

var ttt = new TTT();
ttt.Show();

TTT-class:

public class TTT : Form
{    
    private void button2_Click(object sender, EventArgs e)
    {
        this.Hide();
    }
}

Now call ttt.Show() again within your consumer-code, not the form-class itself.

Alternativly you may set the visibility of the form using Form.Visibility.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
0

You have two options.

  1. Use instance variable instead of class variable and let the things work as it is now.
  2. Don't dispose the form, just live with Show/Hide options.

.

Option 1:

public TTT ttt_local = new TTT();

private void button1_Click(object sender, EventArgs e)
{
    if(ttt_local == null) ttt_local = new TTT(); 
    ttt_local.Show();
}

Option 2:

Don't close the form, just play with hide/show or even set the Visible property.

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

What is the reason of using a global variable? You should only put the variable definition inside the event function:

private void button1_Click(object sender, EventArgs e)
{
    TTT ttt_local = new TTT();
    ttt_local.Show();
}

Whenever the event is triggered, the variable creates and then it disposes with closing the form.

0

You can show it and then hide it like that:

ttt_local.Show();
ttt_local.Hide();

or close:

ttt_local.Close();

Regards.

Feras Al Sous
  • 1,073
  • 1
  • 12
  • 23
S. Medina
  • 76
  • 1
  • 8