简体   繁体   中英

C# WinForms event FormClosing not slove Cannot access a disposed object exception

In my project where i programmatically create new form and show it as dialog all time i get exception:

System.ObjectDisposedException: 'Cannot access a disposed object.'

I try with ClosingEvent but that not work in my project.

Here is my code:

private void productNameTextBox_KeyDown(object sender, KeyEventArgs e)
{
        using (Form productDialog = new Form())
        {
            productDialog.FormClosing += new FormClosingEventHandler(productDialog_FormClosing);

            productDialog.ShowDialog();
        }
}


  private void productDialog_FormClosing(object sender, FormClosingEventArgs e)
    {

        productDialog.Hide();
        productDialog.Parent = null;

        MessageBox.Show("Triggered");     // Showed on close

        e.Cancel = true; //hides the form, cancels closing event

    }

When i close opened dialog on " X " and try again to open it i get exception. Whay e.Cancel not working but message box is showed. What i do wrong?

You have written using (Form productDialog = new Form()) so productDialog Form will be disposed as soon as your productNameTextBox_KeyDown will finish its part. You can read about this here MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM