vb.net删除大量动态创建的按钮 [英] vb.net deleting lots of dynamically created buttons
问题描述
我是vb.net的新程序员,因此可能是无知的道歉。
我正在为数据库接口构建一个简单的gui,其中包含许多父项和子项。在表单上,我创建按钮取决于多少项目(父母/孩子)。我已经创建了按钮:
I'm a new programmer to vb.net, so apologise for what is likely to be ignorance. I’m building a simple gui for a database interface, with many parent and child items within it. Upon a form I create buttons depending on how many items (parents/children). I've got the creation of the buttons thus:
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
但是我正在努力删除按钮,一个新的替代它们...我可以删除一个点击,但我想删除所有的按钮,以这种方式重新创建之前。
But I’m struggling with a way to delete the buttons to make way for a new set to replace them... I can delete a single one upon its click, but I’d like to delete all of the buttons that have been created in this way before re-creating them.
我希望这是有道理的,有一个相当简单的方法来完成这个..?
I hope that makes sense and there is a fairly simple way to accomplish this..?
推荐答案
我将在创建循环中添加一些Tag属性的值。
这将有助于区分按表创建的按钮创建的按钮。
I will add, in your creation loop, some value to the Tag property. This will help to differentiate the buttons created dinamically from the buttons created statically in your form.
Buttoni.Tag = 1
然后,删除一个按钮,按照Me.Controls集合的顺序循环,
检查如果你得到一个按钮,如果标签属性IsNot Nothing
Then, to delete a button, loop in reverse order on the Me.Controls collection,
check if you get a button and if the Tag property 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
这篇关于vb.net删除大量动态创建的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!