How to tell if an object exists

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a form that is created if it is not already created.

The code goes something like this:

if (MyForm == null)
MyForm = new MyForm();
else
MyForm.Activate

The problem is that if the form has been closed with the control box, the
form will not be null, but it will not activate either. So what is the
proper way to check for the form to see if it exists and is activatable?
 
Greg said:
I have a form that is created if it is not already created.

The code goes something like this:

if (MyForm == null)
MyForm = new MyForm();
else
MyForm.Activate

The problem is that if the form has been closed with the control box, the
form will not be null, but it will not activate either. So what is the
proper way to check for the form to see if it exists and is activatable?
Add an eventhandler to the close event of your form and set your
instance to null in this.

MyForm.Closed += new EventHandler(Myfor_Closed);

private void MyForm_Closed(object sender, eventargs e)
{
myform = null;
}

Then it will work properly.
The problem is that you contain a reference (still valid) to a disposed
form which will obviously not allow you to work with it.

Cheers
JB
 
I have a form that is created if it is not already created.

The code goes something like this:

if (MyForm == null)
MyForm = new MyForm();
else
MyForm.Activate

The problem is that if the form has been closed with the control box, the
form will not be null, but it will not activate either. So what is the
proper way to check for the form to see if it exists and is activatable?

This is a common problem and can be solved by the creation of a Singleton
style of form class.

e.g.

public class MyForm
{
private MyForm() : base() {} // hide regular constructor

private static Form2 instance = null;

public static void ShowForm()
{
if (instance == null)
instance = new Form2();
instance.Show();
}

protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
instance = null;
}
}

This is then called like this :

private void button1_Click(object sender, System.EventArgs e)
{
Form2.ShowForm();
}

Joanna
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top