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

标签 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

但是当我重新选择 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/

    相关文章:

    .net - 我如何知道 .net 事件是否已被处理?

    sql - 使用条件(第一个字符)从仅 SQL 项目填充列表框

    vb.net - 我如何使用 vb.net 读取 Excel 工作表的文本框(尝试使用 uipath 调用代码事件自动化流程)

    vb.net - excel oledb 字段在 255 处截断

    c# - c#.net 和 vb.net 中同一 dll 的属性差异

    .net - VB .NET 中的结构,如 COBOL

    c++ - 如何将 unsigned short* 从 Visual-C++ DLL 传递到 VB.NET

    javascript - 关闭弹出窗口时可以刷新父窗口吗?

    c# - 什么是NullReferenceException,如何解决?

    asp.net - VB.NET aspx 页面在 If 语句中使用代码隐藏变量