当前位置 : 主页 > 编程语言 > c语言 >

从VB.net中的ListBox中删除项目

来源:互联网 收集:自由互联 发布时间:2021-06-24
我有两个ListBox1和ListBox2.通过选择ListBox1项,我已使用以下代码将项插入ListBox2: da6 = New SqlDataAdapter("select distinct(component_type) from component where component_name='" ListBox1.SelectedItem() "'", con)da6.Fi
我有两个ListBox1和ListBox2.通过选择ListBox1项,我已使用以下代码将项插入ListBox2:

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 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);
网友评论