从 VB.net 中的 ListBox 中删除项目 [英] Removing items from a ListBox in VB.net

查看:54
本文介绍了从 VB.net 中的 ListBox 中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 ListBox1ListBox2.我已通过选择 ListBox1 项目将项目插入到 ListBox2 中,代码如下:

I have two ListBox1 and ListBox2. I have inserted items into a ListBox2 with the following code by selecting ListBox1 item:

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 显示预加载的项目和现在加载的项目.我只想在列表框中显示现在加载的项目.我使用了这段代码,但问题没有解决:

But when I reselect another item of ListBox1 then ListBox2 shows preloaded items and now loaded item together. I want only now loaded item to be displayed in listbox. I used this code but problem not solved:

For i =0 To ListBox2.items.count - 1
    ListBox2.Items.removeAt(i)
Next

listbox2.items.clear() 也不起作用..

如何清除 ListBox2 中的所有项目?

How can I clear all items in the ListBox2?

推荐答案

简单使用:

ListBox2.Items.Clear()

  • 要考虑您上次的在添加新项目之前执行此操作
  • MSDN:ListBox.ObjectCollection.Clear

    从集合中删除所有项目.

    Removes all items from the collection.

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

    Note that the problem with your approach is that RemoveAt changes the index of all remaining items.

    当您从列表中删除一个项目时,索引更改为列表中的后续项目.有关已删除项目的所有信息被删除.您可以使用此方法从list 通过指定要从列表中删除的项目的索引.到指定要删除的项目而不是项目的索引,使用删除方法.要从列表中删除所有项目,请使用清除方法.

    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,你可以倒退,例如:

    If you want to use RemoveAt anyway, you can go backwards, for example with:

    一个 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# 代码

    old C# code

    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 中的 ListBox 中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆