Reputation: 5248
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?
Upvotes: 0
Views: 381
Reputation: 7706
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
Upvotes: 1