加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 07:12:01 所属栏目:百科 来源:网络整理
导读:我有两个ListBox1和ListBox2.通过选择ListBox1项,我已使用以下代码将项插入ListBox2: da6 = New SqlDataAdapter("select distinct(component_type) from component where component_name='" ListBox1.SelectedItem() "'",con)da6.Fill(ds6,"component")For
我有两个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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读