Cannot access a disposed object

rockwell

Active member
Joined
Dec 6, 2005
Messages
36
Programming Experience
Beginner
Hello all, i am getting an error when trying to access the sub form in vb.net. I created a sub form in vb.net and if i click a button its coming up by calling "subform.Show()", when i close the sub form and try to reopen it its giving me an error saying "Cannot access a disposed object sunform". I guess i am getting this error as i am not releasing the form or something . Any suggestions for this please ...

Thanks for your time ...

--kris
 
when you close a form it gets disposed so if you need to show it again you need to make a new instance by using the 'New' keyword before showing it again. ex:
VB.NET:
Private frm As Form1

'A button or menu item's click event:
frm = New Form1
frm.Show()

in your case replace 'frm' with 'subform'

another alternative is to never close the form, just hide it
in the subform's closing event:
VB.NET:
e.Cancel = True
Me.Hide
 
Closing a modeless form (Show) is actually Disposing it.
You cannot use a disposed object (as you just found out): resources are freed, etc..
Just create a new instance of the form, or as an alternative hide the modeless form instead of closing it. Another possibility is showing the form modal (with ShowDialog). Closing a modal form in fact just hides the form.

Best practice in most cases (there are some exceptions) is creating a new instance. Even when using ShowDialog, but then you'll have to call Close (or Dispose) yourself.

Edit: I see JuggaloBrotha was a lot faster to hit the submit button :eek:
 
Last edited:
Back
Top