Search code examples
vb.netcontrolsdisposedynamically-generated

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

Solution

  • 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