我有这段代码,我想知道如何删除表单中所有已创建的标签。
我试图将lbl.dispose()和ltr.dispose()放在Button上,但它表示它没有声明或无法访问。
Dim break As Integer = 99
For i = 0 To break
If jobA > 0 And jobA > time Then
jobA = jobA - time
Dim lbl As Label = New Label
Dim ltr As Label = New Label
lbl.Location = New System.Drawing.Point(x, 280)
lbl.Size = New System.Drawing.Point(20, 20)
lbl.Text = time + spudow(waifuu)
ltr.Location = New System.Drawing.Point(y, 250)
ltr.Size = New System.Drawing.Point(20, 20)
ltr.Text = "A"
Me.Controls.Add(lbl)
Me.Controls.Add(ltr)
ElseIf jobA > 0 And jobA < time Then
Dim lbl As Label = New Label
Dim ltr As Label = New Label
lbl.Location = New System.Drawing.Point(x, 280)
lbl.Size = New System.Drawing.Point(20, 20)
lbl.Text = jobA + spudow(waifuu)
ltr.Location = New System.Drawing.Point(y, 250)
ltr.Size = New System.Drawing.Point(20, 20)
ltr.Text = "A"
Me.Controls.Add(lbl)
Me.Controls.Add(ltr)
ElseIf jobA = time Then
Dim lbl As Label = New Label
Dim ltr As Label = New Label
lbl.Location = New System.Drawing.Point(x, 280)
lbl.Size = New System.Drawing.Point(20, 20)
lbl.Text = jobA + spudow(waifuu)
ltr.Location = New System.Drawing.Point(y, 250)
ltr.Size = New System.Drawing.Point(20, 20)
ltr.Text = "A"
Me.Controls.Add(lbl)
Me.Controls.Add(ltr)
End If
Me.Refresh()
答案 0 :(得分:2)
我喜欢Zaggler使用List(Of Label)的想法,但我会使用标签的.Tag属性发布另一种方法。如果所有标签只会添加到表单本身,这将足够好。如果您要将标签分布在多个容器中,则使用List(Of Label)方法,因为它会更容易。另外,你可以通过这样重组来摆脱大量冗余代码(我假设有更多未显示的代码以某种方式改变了“x”和“y”值!):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim break As Integer = 99
For i = 0 To break
Dim lbl As Label = New Label
Dim ltr As Label = New Label
lbl.Tag = "dynamic"
ltr.Tag = "dynamic"
lbl.Location = New System.Drawing.Point(x, 280)
lbl.Size = New System.Drawing.Point(20, 20)
lbl.Text = ""
ltr.Location = New System.Drawing.Point(y, 250)
ltr.Size = New System.Drawing.Point(20, 20)
ltr.Text = "A"
If jobA > 0 Then
If jobA > time Then
jobA = jobA - time
lbl.Text = time + spudow(waifuu)
ElseIf jobA < TimeOfDay Then
lbl.Text = jobA + spudow(waifuu)
End If
ElseIf jobA = time Then
lbl.Text = jobA + spudow(waifuu)
End If
If lbl.Text <> "" Then
Me.Controls.Add(lbl)
Me.Controls.Add(ltr)
End If
Next i
End Sub
然后,当您想要删除动态标签时,您可以使用以下代码:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim labels = Me.Controls.OfType(Of Label).Where(Function(x) x.Tag = "dynamic").ToList
For Each lbl As Label In labels
lbl.Dispose()
Next
End Sub
答案 1 :(得分:-2)
Sub RemoveAllLabels()
Dim Labels As New List(Of Label)
Dim Stack As New Stack(Of Control)
Stack.Push(Me)
While Stack.Count > 0
Dim Ctrl As Control = Stack.Pop()
Labels.Add(TryCast(Ctrl, Label))
For Each C As Control In Ctrl.Controls
Stack.Push(C)
Next
End While
For Each L As Label In Labels
If Not IsNothing(L) Then L.Dispose()
Next
End Sub