cannot access a disposed object

  • Thread starter Thread starter Bernie Yaeger
  • Start date Start date
B

Bernie Yaeger

I'm launching one window from another. I have a close button in the first
window and when I click it, it executes me.close. However, the form also
has a treeview control. If I launch the second window on a treeview node
selection, the second window launches just fine; however, if I have me.close
in the code right after it, I get the error 'cannot access a disposed object
called 'treeview'. This even happens if I simply call closeit.performclick.

If I do nothing, I can click the close button and I don't get an error.
What's going on here?

Tx for any help.

Bernie Yaeger
 
Hi Bernie,

This is one that crops up a lot. When you are in the event handler for a
control such as a TreeView (last time it was a DataGrid), you are deep in the
call stack (have a look at the stack trace).

When your handler exits, control goes back up this stack of calls as they
in their turn finish off what they were doing and exit. The effect of Me.Close
is to Dispose of the Form, including all of the Controls that it contains.
Bye-bye Form, bye-bye TreeView.

The trouble is, the TreeView event-handling code is somewhere in that
stack waiting to do its finishing off - and there's no TreeView anymore. Bang!

One solution is to not close the Form in the event handler. Not what you
want, I imagine. Another is to hide it and close it by some other means. One
of these is to have a Timer (use System.Timers) set to go off in a few
millisecs. The Tick event handler would stop the Timer and then close the
Form.

Regards,
Fergus
 
Back
Top