从表单动态创建和删除控件很多次

时间:2013-09-17 23:40:39

标签: vb.net controls dispose dynamically-generated

当使用鼠标单击调用时,以下子例程成功创建然后删除控件。但它不是第二次创造它。我假设这是因为标签的尺寸不再公开。即Dim lblDebug1 As New Label位于表单的顶部变量部分。 但是,当我将Dim lblDebug1 As New Label放在子例程中时,dispose请求不起作用。有没有我可以继续创建和处理控件?

在下面的子项中,booleanDebug用于在创建和处理它之间来回切换。提前谢谢

Dim lblDebug1 As New Label

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

2 个答案:

答案 0 :(得分:2)

确保标签具有全局上下文。在拥有它的表单中,您拥有所有适当的大小和坐标信息和可见性集。

以下是一些适合我的示例代码。首先,只需创建一个新窗体,然后在窗体中间添加一个按钮控件,然后使用以下代码。

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

答案 1 :(得分:1)

一旦你设置了一个控件,你就不能再使用它了。你有两个选择:

选择1:只需从表单中删除控件而不是将其丢弃:

'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

选择2:每次都创建一个新控件对象

'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