我是vb.net的新程序员,所以为可能无知而道歉。 我正在为数据库接口构建一个简单的gui,其中包含许多父项和子项。在表单上,我根据有多少项目(父母/孩子)创建按钮。我已经创建了按钮:
For RowNumber As Integer = 0 To NoOfRows
Dim Buttoni As New Button
Buttoni.Location = New Point(LocationX, LocationY)
Buttoni.Width = 100
Buttoni.Height = 40
Buttoni.Visible = True
Buttoni.Text = DatasetA.Tables(0).Rows(RowNumber).Item("Name")
ButtonName = "Button" + RowNumber.ToString
If LocationX < FormWidth - (SpacePerButtonX * 2) Then
LocationX = LocationX + SpacePerButtonX
Else
LocationX = 50
LocationY = LocationY + SpacePerButtonY
End If
AddHandler Buttoni.Click, AddressOf DynamicButtonClick
Me.Controls.Add(Buttoni)
Buttoni.BringToFront() 'brings newest buttons to front!
Next
但是我正在努力想要一种删除按钮的方法,让新的设备替换它们...我可以在点击时删除一个,但我想删除所有的按钮在重新创建之前已经以这种方式创建。
我希望这是有道理的,并且有一种相当简单的方法可以实现这一目标。?
答案 0 :(得分:3)
我将在您的创建循环中为Tag属性添加一些值。 这将有助于区分创建的按钮与您在表单中静态创建的按钮。
Buttoni.Tag = 1
然后,要删除按钮,请在Me.Controls集合上按相反顺序循环,
检查是否有一个按钮,以及Tag属性IsNot Nothing
For x as Integer = Me.Controls.Count - 1 to 0 step -1)
Dim b as Button = TryCast(Me.Controls(x), Button)
If b IsNot Nothing AndAlso b.Tag IsNot Nothing then
b.Dispose() '' NOTE: disposing the button also removes it
End If
Next
答案 1 :(得分:1)
很难确切地知道你想做什么。我想你可以反过来使用相同的技术,比如
For i As Integer = Me.Controls.Count - 1 To 0 Step -1
Dim ctrl = Me.Controls(i)
If TypeOf (ctrl) Is Button Then
ctrl.Dispose() '' NOTE: disposing the control also removes it
End If
Next
答案 2 :(得分:0)
创建一个按钮并双击删除它! 简易代码:
Dim b As New Button
Private btn As Button ' this is a reference object
Private ptX, ptY As Integer
Private drag As Boolean
Private Sub nodebtn_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If e.Clicks = 2 Then
b.Dispose()
End If
If e.Button = MouseButtons.Left Then
drag = True
btn = CType(sender, Button)
ptX = e.X : ptY = e.Y
End If
End Sub
Private Sub nodebtn_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If drag Then
btn.Location = New Point(btn.Location.X + e.X - ptX, btn.Location.Y + e.Y - ptY)
Me.Refresh()
End If
End Sub
Private Sub nodebtn_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
drag = False
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
b.Location = New Point(10, 10)
b.Size = New Size(110, 29)
b.BringToFront()
b.Text = "Button"
AddHandler b.MouseDown, AddressOf nodebtn_MouseDown
AddHandler b.MouseMove, AddressOf nodebtn_MouseMove
AddHandler b.MouseUp, AddressOf nodebtn_MouseUp
Me.Controls.Add(b)
End Sub