Consider the following code in Form1:
Dim frmDet As New frmDetails
Private Sub cmdShowDetails_Click()
frmDet.Show
End Sub
VB Migration Partner correctly converts this deceptively simple code, but the migrated VB.NET code has a problem: The first time the end user clicks on the cmdShowDetails button, the secondary form appears correctly; however, if the secondary form is closed and then the cmdShowDetails button is clicked again, the Show method throws an ObjectDisposed exception.
The problem occurs because all closed .NET forms are automatically disposed and there is no way for the VB6Form class (which inherits from System.Windows.Forms.Form) to change this behavior. The problem occurs regardless of whether the secondary form is modal or modeless.
Oddly, the problem does not occur if you use the frmDetails default form instance, as in:
frmDetails.Show
Unfortunately, there is no way of solving this problem short of modifying either the original VB6 code or the converted VB.NET code. Here are three possible solutions:
- Use the form’s default instance.
The problem goes away if you use the default form instance that made available by VB.NET. In previous example you’d just need to get rid of the frmDet variable and replace the Show statement as follows:
Private Sub cmdShowDetails_Click()
frmDetails.Show
End Sub
This is the simplest solution if you don’t have to display multiple occurrences of the same form
- Recreate the form each time you show it.
This is also a very simple solution which has no drawbacks and preserves functional equivalence:
Dim frmDet As frmDetails
Private Sub cmdShowDetails_Click()
Set frmDet = New frmDetails
frmDet.Show
End Sub
- Hide the secondary form instead of closing it.
This solution is preferable if the secondary form is recalled from many places of the application, because you just need to change the code inside the secondary form (and not in all methods that show the form). The simplest method to apply this fix is by intercepting the FormClosing event in the VB.NET code:
Protected Overrides Sub OnFormClosing(ByVal e As FormClosingEventArgs)
MyBase.OnFormClosing(e)
e.Cancel = True
Me.Hide()
End Sub
The drawback of this third solution is that the hidden form appears in the Forms collection and that – when shown again – it is in the same state as it was when it was hidden: fields contains the same values, variables are not reset, etc. For this reason, this is the least preferable solution of the three.