我有两个 ListBox1
和 ListBox2
.我已将项目插入 ListBox2
使用以下代码选择 ListBox1
元素:
da6 = New SqlDataAdapter("select distinct(component_type) from component where component_name='" & ListBox1.SelectedItem() & "'", con)
da6.Fill(ds6, "component")
For Each row As DataRow In ds6.Tables(0).Rows
ListBox2.Items.Add(row.Field(Of String)("component_type"))
Next
但是当我重新选择
ListBox1
的另一个项目时然后 ListBox2
一起显示预加载的项目和现在加载的项目。我只想在列表框中显示现在加载的项目。
我使用了这段代码,但问题没有解决:
For i =0 To ListBox2.items.count - 1
ListBox2.Items.removeAt(i)
Next
或者
listbox2.items.clear()
也不行。。如何清除
ListBox2
中的所有项目?
最佳答案
简单地使用:
ListBox2.Items.Clear()
MSDN:
ListBox.ObjectCollection.Clear
Removes all items from the collection.
请注意,您的方法的问题在于
RemoveAt
更改所有剩余项目的索引。When you remove an item from the list, the indexes change for subsequent items in the list. All information about the removed item is deleted. You can use this method to remove a specific item from the list by specifying the index of the item to remove from the list. To specify the item to remove instead of the index to the item, use the Remove method. To remove all items from the list, use the Clear method.
如果您想使用
RemoveAt
无论如何,您可以倒退,例如:for
-环形:For i As Int32 = ListBox2.Items.Count To 0 Step -1
ListBox2.Items.RemoveAt(i)
Next
或
while
While ListBox2.Items.Count > 0
ListBox2.Items.RemoveAt(ListBox2.Items.Count - 1)
End While
旧的 C# 代码
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
ListBox2.Items.RemoveAt(i);
while(ListBox2.Items.Count > 0)
ListBox2.Items.RemoveAt(ListBox2.Items.Count - 1);
关于vb.net - 从 VB.net 中的 ListBox 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14379438/