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

use*_*423 3 vb.net

我有两个ListBox1ListBox2.我已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
Run Code Online (Sandbox Code Playgroud)

但是当我重新选择另一个项目ListBox1然后ListBox2显示预装项目和现在加载的项目.我只希望现在加载的项目显示在列表框中.我使用了这段代码,但问题没有解决:

For i =0 To ListBox2.items.count - 1
    ListBox2.Items.removeAt(i)
Next
Run Code Online (Sandbox Code Playgroud)

或者 listbox2.items.clear()也没有工作..

如何清除所有项目ListBox2

Tim*_*ter 8

使用简单:

ListBox2.Items.Clear()
Run Code Online (Sandbox Code Playgroud)
  • 要考虑上次编辑:添加新项目之前执行此操作

MSDN: ListBox.ObjectCollection.Clear

从集合中删除所有项目.

请注意,您的方法的问题是RemoveAt更改所有剩余项目的索引.

从列表中删除项目时,索引会更改列表中的后续项目.删除有关已删除项目的所有信息.您可以使用此方法通过指定要从列表中删除的项目的索引来从列表中删除特定项目.若要指定要删除的项而不是项的索引,请使用Remove方法.要从列表中删除所有项目,请使用"清除"方法.

RemoveAt无论如何你想要使用,你可以倒退,例如:

a for-loop:

For i As Int32 = ListBox2.Items.Count To 0 Step -1
    ListBox2.Items.RemoveAt(i)
Next
Run Code Online (Sandbox Code Playgroud)

或者a while

While ListBox2.Items.Count > 0
    ListBox2.Items.RemoveAt(ListBox2.Items.Count - 1)
End While
Run Code Online (Sandbox Code Playgroud)

旧的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);
Run Code Online (Sandbox Code Playgroud)


小智 5

这段代码对我有用:

ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)