我是一个新的程序员vb.net,所以什么可能是无知道歉。 我建立一个简单的图形用户界面的数据库接口,与内部了很多家长和孩子的物品。 在一个形式取决于有多少项目(父母/子女)我创建按钮。 我有这样的按钮创建:
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
但我有一个方法来删除的按钮来让路了一套新的来代替它们挣扎......我可以删除在其单击一个一个,但我想删除所有已创建的按钮在此之前的方式重新创建它们。
我希望是有道理的,有一个非常简单的方法来做到这一点..?
我将增加,在你的创作循环,一定的参考价值Tag属性。 这将有助于区分表单中的静态创建按钮dinamically创建的按钮。
Buttoni.Tag = 1
然后,删除以相反的顺序一个按钮,环路上Me.Controls收集,
检查如果你得到一个按钮,如果标签属性状态并没有没有
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
这是很难知道你想要做什么。 我想你可以只使用相同的技术在倒车时,像
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
创建一个按钮,并双击它删除! 方便的代码:
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