hkguile
hkguile

Reputation: 4369

open new winform using singleton pattern

i have a form like this, i want to use singleton to make sure only one instance is running

private static productForm instance;
public productForm()
{
    InitializeComponent();
}

public static productForm GetInstance
{
    get
    {
        if (instance == null)
        {
            instance = new productForm();
        }
        return instance;
    }
}

/*private void productForm_FormClosed (object sender, FormClosingEventArgs e)
{
    instance = null;
}*/

}

In mainform click event

    private void categoryTreeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        productForm.GetInstance.Show();

    }

There is a bug when i closed the productform, there is an error when i try to reopen it.

The productForm.GetInstance.Show(); will output an error message "Cannot access a disposed object", seems productForm is not accessible, anyone know what is the problem?

Upvotes: 1

Views: 2959

Answers (1)

rishit_s
rishit_s

Reputation: 350

try this

private static productForm instance;
public productForm()
{
  InitializeComponent();
}

public static productForm GetInstance
{
get
{
    if (instance == null || instance.IsDisposed)
    {
        instance = new productForm();
    }
    return instance;
}
}

Upvotes: 4

Related Questions