Dynamically Generated Form Problem

Doug

Active member
Joined
Oct 5, 2011
Messages
44
Programming Experience
Beginner
Hi guys,

I have a dynamically generated form. It is just a ListBox in a form container. It opens perfectly fine the first time but the second time I get an error. Here is the string of code that leads to the error:

User closes the first mealForm and this executes:

Private Sub mealFormClosed()
'Clears the object when the form closes
mealForm = Nothing
End Sub

Then user clicks on the button again and the following executes:


Public Sub Show(ByRef bugList As List(Of BaseBug))
'Shows the form
If mealForm Is Nothing Then
Dim mealForm As New Form
Dim mealsListBox As New System.Windows.Forms.ListBox()
initializeForm()

Public Sub initializeForm()
'
'mealsListBox
'
mealForm.SuspendLayout()

The error happens as the line about "mealForm.SuspendLayout()" Error: Object reference not set to an instance of an object



The rest of the code for the object is below. What am I doing wrong?


Public Class MealsDisplay

Public mealForm As New Form
Public mealsListBox As New System.Windows.Forms.ListBox()


Public Sub Show(ByRef bugList As List(Of BaseBug))
'Shows the form
If mealForm Is Nothing Then
Dim mealForm As New Form
Dim mealsListBox As New System.Windows.Forms.ListBox()
initializeForm()
End If
Dim targetListBox As ListBox = CType(mealsListBox, ListBox)
mealForm.Show()
For Each bug As BaseBug In bugList
targetListBox.Items.Add(bug.CommonName)
Next
End Sub



Public Sub New() initializeForm()
End Sub


Public Sub initializeForm()
'
'mealsListBox
'
mealForm.SuspendLayout()
mealsListBox.BorderStyle = System.Windows.Forms.BorderStyle.None
mealsListBox.Enabled = False
mealsListBox.FormattingEnabled = True
mealsListBox.Location = New System.Drawing.Point(1, 1)
mealsListBox.Name = "mealsListBox"
mealsListBox.Size = New System.Drawing.Size(256, 156)
mealsListBox.TabIndex = 0
'
'MealsForm
'
With mealForm
.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
.ClientSize = New System.Drawing.Size(256, 158)
.Controls.Add(mealsListBox)
.Name = "MealsForm"
.Text = "MealsForm"
.ResumeLayout(False)
End With


AddHandler mealForm.FormClosed, AddressOf Me.mealFormClosed


End Sub


Private Sub mealFormClosed()
'Clears the object when the form closes
mealForm = Nothing
End Sub
End Class


 
I found the problem. When the form is closed it is disposed. Since it was declared at the class level I cannot re-declare it at the local level.

I fixed this by declaring it only at the local level and passing the objects as parameters to my other procedures.
 
Back
Top