ALX
Well-known member
I have recreated an error that I'm running into with this simple example. Clicking the "GO" button the first time generates an owned form that displays a few ListBoxes that were initalized in the parent form. Clicking the "GO" button a second time should dispose of the original owned form & create a new version of it. Instead it generates a runtime error:
"Cannot access a disposed object.
Object name: 'ListBox'."
I can step through the code where these ListBoxes are added to the owned form (both initially and the second time around), and the ListBoxes appear to be very much alive. It's when I call Form2.Show() the second time that the error occurs. Would any guru kindly enlighten a newbie here ???
Here is code for Form1:
and here is code for Form2:
"Cannot access a disposed object.
Object name: 'ListBox'."
I can step through the code where these ListBoxes are added to the owned form (both initially and the second time around), and the ListBoxes appear to be very much alive. It's when I call Form2.Show() the second time that the error occurs. Would any guru kindly enlighten a newbie here ???
Here is code for Form1:
VB.NET:
Public Class Form1
Friend WithEvents Frm2 As Form
Friend WithEvents ULB As New System.Windows.Forms.ListBox
Friend WithEvents SLB As New System.Windows.Forms.ListBox
Friend WithEvents XLB As New System.Windows.Forms.ListBox
Dim Progress As Int16 = 0
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim j As Int16
For j = 1 To 10
ULB.Items.Add(j.ToString)
SLB.Items.Add(j + 20.ToString)
XLB.Items.Add(j + 40.ToString)
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Progress = 0 Then
NewInstance()
Progress += 1
Else
CloseFrm2()
NewInstance()
End If
End Sub
Private Sub CloseFrm2()
If Not Frm2 Is Nothing Then
Frm2.Close()
Frm2.Dispose()
Application.DoEvents()
End If
End Sub
Private Sub NewInstance()
Frm2 = New Form2(ULB, SLB, XLB)
Me.AddOwnedForm(Frm2)
Frm2.Location = New Point(20, 20)
Frm2.Show()
End Sub
End Class
VB.NET:
Public Class Form2
Friend Sub New(ByRef ULB As ListBox, ByRef SLB As ListBox, ByRef XLB As ListBox)
InitializeComponent()
Me.Controls.Add(ULB)
ULB.Location = New Point(25, 35)
ULB.Height = 100
ULB.Width = 50
ULB.Show()
Me.Controls.Add(SLB)
SLB.Location = New Point(100, 35)
SLB.Height = 100
SLB.Width = 50
SLB.Show()
Me.Controls.Add(XLB)
XLB.Location = New Point(175, 35)
XLB.Height = 100
XLB.Width = 50
XLB.Show()
End Sub
End Class
Last edited: