4

下面的子例程,当使用鼠标单击调用时,成功创建然后删除控件。但它不会第二次创建它。我假设这是因为标签不再是公开的。ieDim lblDebug1 As New Label位于表单的顶部变量部分。但是,当我放入Dim lblDebug1 As New Label子程序时,处置请求不起作用。有什么方法可以让我继续创建和处理控件吗?

在下面的 sub 中,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
4

2 回答 2

3

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

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

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
于 2013-09-18T00:04:40.903 回答
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
于 2013-09-20T21:17:13.463 回答