Cannot access disposed form despite creating it immediately prior - vb.net

I have a windows form (VB/.NET) that I want to open when I click a particular button. It opens correctly the first time, but after closing it and trying to re-open it I get this error:
"ObjectDisposedException was unhandle: Cannot access a disposed object. Object name: frm8100VI"
Now, I create a new instance of the form right before calling it's show() method, so I don't know how it's disposed:
Dim form as New frm8100VI
form.show()
This code works correctly the first time it's called, but after closing the form once it will not work correctly again, saying the object has been disposed. To close the form all I do is call me.close()

I'm guessing you have your "Dim form as new frm8100VI" located in a space inside another object or in a public space where it never goes out of scope.
Once you have said "form.show", the user has worked with the form, closes the form.
At this point you cannot call "form.Show" again on the same form object (it is disposed).
You MUST reassign "form = New frm8011VI" again before you can call "form.show" (to re-iterate, after it has been disposed show fails)
If your trying to persist the information inside the "form" object then you should not actually close the form; in the form_unload event you show cancel the closing of the form and simply hide the form. If you do that you can call "form.Show" again without issue.

Related

How should you reload a form and have it re-initialize?

A older application loads some forms using implicit instances:
form2.showdialog()
Sometime between VS2008 32-bit and VS2013 64-bit, the forms stopped being initialized when they are reloaded. For example, if you load a form, close the form (using the Close method), and load the form again, the classes and controls (and, I assume, the form) are not initialized as new instances.
Re-initialization can be accomplished by putting me.dispose() in the FormClosed event, or by using an explicit instance of the form:
Using frm As New Form2
frm.ShowDialog()
End Using
Is there a good reason to use one of these methods over the other, or is there another method that should be used to cause a form to be initialized when it is reloaded?
Dispose will be called automatically if the form is shown using the Show method. If another method such as ShowDialog is used (your case it is), or the form is never shown at all, you must call Dispose yourself within your application. You can also handle the dispose by moving it from the designer file into the code file and handle things there as well.
On the other hand, Using statement typically makes your application safer to maintain and less prone to deadlocks and other misbehavior related to the lifecycle of the resource. I would stick by using this approach.
Also you cant put Me.Dispose in the Form Closed event (possible issues). If your using ShowDialog it will fail as it will dispose your objects first, if you need them they are gone.
Here's more on dispose: https://msdn.microsoft.com/en-us/library/aw58wzka(v=vs.110).aspx
The Form object and its child controls are not automatically disposed when you display the form with ShowDialog(). That sounds pretty quirky but this was done for a very good reason. After ShowDialog returns DialogResult.OK, you are normally going to obtain the dialog results. What nobody likes is that failing because of a ObjectDisposedException. Which would be likely to occur since the dialog results are often stored in controls.
You should always use the Using statement to ensure the form object and all of its controls are disposed.
A possible corner case is intentionally not disposing it because you like the redisplay the dialog with the original entered values. Which is not completely wrong, it is however a very expensive way to preserve those values. Those undisposed window objects cost an arm and a leg in system resources.
Pretty clear explanation from MSDN
Unlike non-modal forms, the Close method is not called by the .NET
Framework when the user clicks the close form button of a dialog box
or sets the value of the DialogResult property. Instead the form is
hidden and can be shown again without creating a new instance of the
dialog box. Because a form displayed as a dialog box is hidden instead
of closed, you must call the Dispose method of the form when the form
is no longer needed by your application.
When ShowDialog() called and closed, instance of the form will remain in the memory, and can be used again, for example get a result from some public property.
If you not using anymore this form, you need to call Dispose method to dispose form and form's controls
Dim myform As New MyDialogForm()
myform.ShowDialog()
Dim result As Object = myForm.SelectedResult()
myform.Dispose() 'need to call manually, if instance not used anymore
When you use Using keyword then Dispose method will be executed automatically at the end of the Using block
Dim result As Object
Using myform As New MyDialogForm()
myform.ShowDialog()
result = myForm.SelectedResult()
End Using 'myform.Dispose will be called
Bottom line: Both methods doing a same things.
But Using block will call Dispose method automatically
P.S. Putting Me.Dispose in the FormClosed eventhandler then
- instance of the form will stay in the memory even form was closed
- and will work only until you tried using disposed controls again. If you will try to show disposed object then ObjectDisposedException will be thrown.
If you not using form anymore then Using block will be best method

Opening a second-form more than once error

I have a button in form1 that opens form2. I do this using frm2.show(). It works totally fine for the first time that I open frm2, but when I close frm2 and click on the button in frm1 to open frm2 again, I get this error:
Can someone tell me how to solve it?
Edit: I have a module where I have my database connection and my declaration for the forms:
Public frmGame As New Game
Public frmPlay As New Play
Public frmFinish As New GameFinish
Public frmLogin As New Login
Public frmManage As New Manage
Public frmInsert As New Toevoegen
Where I open the form is just when I click on a button in form1.
Sounds to me like you are Close()ing frm2. Closing a form should dispose it and release its resources, so you can't simply Show() it again. Instead, you need to create a new instance of the object, like this:
frm2=new Form2()
frm2.Show()
If that doesn't work (perhaps because you don't want to re-initialize the form's data members), you could use Hide(), rather than Close() to temporarily hide the form during your program's execution.
If you need to prevent the form from being closed with the X button, you can do this with a few different methods:
The best way to go may be to hide or disable the close button. Read up on This post to get a better idea of how to do that.
You can use the FormClosing event, either from inside frm2 or from the main window. Set the Cancel property on the FormClosingEventArgs object that gets passed in. The problem here is that you will need to provide an additional code path to close the form when you actually want it to close. The CloseReason property of the FormClosingEventArgs object should give you a way to handle that properly. Needless to say, this is probably the riskiest way to do things, since you need this window to close when the application shuts down, but you're also intentionally block that from happening.
You could catch the FormClosed event in the the form that spawns frm2, then create a new instance of the window. Again, you'll need to provide a code path to allow the window to close when the application shuts down.
In all, method 1 is probably the safest. You can close the window with .Close() when the application shuts down, but the user can't close it with the X button.

Difference form.Close() and form.hide()

What is the difference between form.Close() and form.Hide() in desktop application.
i know Form_Close event will not be fired in form.Hide() method what about other differences.
Is anyone faster?
form.Close() unloads the form from memory and makes it available to be garbage collected; you can no longer interact with the form in code.
form.Hide() just hides the form, but you can still interact with it in your code.
So it is not really a question of which one is faster, but rather "are you really done using this form or not"?
Hide makes the form invisible to the user. Close actually closes it and calls dispose on it.
From: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.close(v=vs.110).aspx
"When a form is closed, all resources created within the object are closed and the form is disposed. "
Hide only hides the form from the screen. Close is of course closes the form. If you want to get rid of the form that you don't want to use anymore then you should use Close. Hide and Close are different things.
Ditto the above... Typically the way you open the form determines which to use. If you use .Show() the calling code continues while the form is loaded and shown. If you use ShowDialog() then calling code stops while the form is loaded and shown. When you Hide the called form the calling code resumes to the next statement.
Here is a sample of the second case:
Dim frm As New frmSearch2
frm.inFormName = "frmFacility"
frm.ShowDialog(Me)
If frm.outPrimaryKey.Length > 0 Then
frmMain.Open_Form("frmFacility", frm.outPrimaryKey)
End If
frm.Close
frm = Nothing
outPrimaryKey is a form level Public variable. You can also address any of the controls on the form.

Error Closing a Form Through a User Control

In the program I'm writing, there is just one form. I've made a user control visible and it contains several buttons. One of the buttons is supposed to close the form when clicked. I can't find any way to do this without getting the error: "Cannot access a disposed object. Object name: 'ShapeContainer.'" I'm pretty sure I understand the problem; after the form has been closed, the user control no longer exists, so there's an error when Form.Close() (I've tried Form.Dispose() too) has completed and it tries to go back to the code inside the button click event. Does anyone know how I could accomplish closing the form through this user control's button without getting the error?
Okay I'm pretty new to vb but I think if you get rid of the Form.Dispose() & Form.Close then try Me.Close() as you are referring to the current Form that the button control is located on.
You Should have got this error:
(Error 1 'NameSpace_.Form1' cannot refer to itself through its default instance; use 'Me' instead.)

Cannot access disposed object .NET

I have a windows form in .NET that will serve as a wizard to achieve something. This contains 3 steps: Step1, Step2, Step3.
Each step is again actually a user control. Main form contains a panel that display the current Step. When I change among steps then:
1) Dispose the current user control by calling its Dispose() method.
2) Clears the main form panel
3) Initialize the user control of next step and add it into the main panel
Now, the issue is, User control of step one contains one more user control. When I change to another step and come back to step 1, I get following error:
"Cannot access disposed object."
Because I have to first dispose the user control before actually displaying the another step. And when I come back to step 1 and tries to open the user control on step 1, it gives the aforementioned error.
Everything in the Controls collection of a Control is disposed when the control is disposed. So if you need to reuse those user controls, you'll need to remove them from the parent user control before disposing it.
You don't actually have to dispose the user control before displaying the next one. You can just remove it from the main form and put the new one on the main form when the step changes. Keep your user controls in a list or a dictionary and dispose them all when the main form is closing.
Why do you need to dispose the user control? Typically, when the form closes, it will dispose of all of it's child controls for you.
When you call dispose on an object, you are essentially telling it to go away.. you don't want it anymore. You can't change your mind -- once it's disposed, it's gone. Don't try to use it anymore.
Typically, you don't call dispose on an object directly; you should use the "using" pattern to avoid disposing of an object before you need it again, and to ensure the object is disposed once you are done with it.