David K
David K

Reputation: 55

Dynamically create and remove a control from a form, many times

The below subroutine, when called using a mouse click, successfully creates and then removes a control. but it doesn't create it a second time. I'm assuming it is because the label is not longer dimensioned as public. ie Dim lblDebug1 As New Label is at the top variable section of the form. However when I put Dim lblDebug1 As New Label in the subroutine the dispose request doesn't work. Is there someway that I can keep creating and disposing a control?

In the below sub, booleanDebug is used to switch back and forth between creating it and disposing it. Thanks in advance.

Dim lblDebug1 As New Label

booleanDebug = Not booleanDebug
  If booleanDebug Then
      Me.Controls.Add(lblDebug1)
      lblDebug1.BackColor = Color.BlueViolet
  Else
      lblDebug1.Dispose()
  End If

Upvotes: 4

Views: 33380

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

Once you've Disposed a control, you can't use it any more. You have two choices here:

Choice 1: Just Remove the control from the form rather than disposing it:

'Top of the file
Dim lblDebug1 As New Label

'Button click
booleanDebug = Not booleanDebug
If booleanDebug Then 
    lblDebug1.BackColor = Color.BlueViolet
    Me.Controls.Add(lblDebug1)       
Else
    Me.Controls.Remove(lblDebug1)
End If

Choice 2: Create a new control object each time

'Top of the file
Dim lblDebug1 As Label
'               ^   No "New". 
'We just want an object reference we can share at this point, no need for an instance yet

'Button click
booleanDebug = Not booleanDebug
If booleanDebug Then
    lblDebug1 = New Label()
    lblDebug1.BackColor = Color.BlueViolet
    Me.Controls.Add(lblDebug1)
Else
    lblDebug1.Dispose()
End If

Upvotes: 1

jcwrequests
jcwrequests

Reputation: 1130

Ensure the label has a global context. Within the form that owns it and that you have all the appropriate size and coordinates information and visibility set.

Here is some sample code that worked for me. First just create a new windows form then add a button control in the middle of the form then use the following code.

Public Class Main
Private labelDemo As Windows.Forms.Label

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.SuspendLayout()

    If labelDemo Is Nothing Then

        labelDemo = New Windows.Forms.Label
        labelDemo.Name = "label"
        labelDemo.Text = "You Click the Button"
        labelDemo.AutoSize = True
        labelDemo.Left = 0
        labelDemo.Top = 0
        labelDemo.BackColor = Drawing.Color.Violet
        Me.Controls.Add(labelDemo)

    Else
        Me.Controls.Remove(labelDemo)
        labelDemo = Nothing
    End If

    Me.ResumeLayout()

End Sub
End Class

Upvotes: 3

Related Questions