3

我是 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

但是我正在努力寻找一种删除按钮的方法,以便为新的一组替换它们让路……我可以在单击时删除一个按钮,但我想删除所有已创建的按钮以这种方式在重新创建它们之前。

我希望这是有道理的,并且有一种相当简单的方法可以实现这一点..?

4

3 回答 3

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
于 2012-06-02T19:28:50.037 回答
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
于 2012-06-02T19:27:47.560 回答
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
于 2015-07-23T09:51:39.007 回答