vb.net 这段删除列表框重复项的代码给了我一个错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16995358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:52:56  来源:igfitidea点击:

This code to remove listbox duplicate items gives me an error

vb.net

提问by user1785594

 Private Sub CHKDUP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKDUP.Click

        Dim i As Long
        Dim j As Long
        With GlinkList
            For i = 0 To GlinkList.Items.Count - 1
                For j = GlinkList.Items.Count To (i + 1) Step -1
                    If GlinkList.Items(j) = GlinkList.Items(i) Then
                        GlinkList.Items.Remove(j)
                    End If
                Next
            Next
        End With

    End Sub

When I press the button, it gives me 'Unhandeled exception has occurred in your applcation, InvalidArgument=Value of '975<-Listbox I tems' is not valid for 'index'. Parameter name: index

当我按下按钮时,它给我“您的应用程序中发生了未处理的异常,InvalidArgument=Value of '975<-Listbox I tems' 对 'index' 无效。参数名称:索引

采纳答案by LarsTech

I think it would probably be easier to just copy the list first, then put the unique results back:

我认为先复制列表可能会更容易,然后将唯一结果放回去:

Dim items(GlinkList.Items.Count - 1) As Object
GlinkList.Items.CopyTo(items, 0)
GlinkList.Items.Clear()
GlinkList.Items.AddRange(items.AsEnumerable().Distinct().ToArray())

回答by invisal

Try this (not yet test, because I don't have Visual Studio in my computer right now)

试试这个(还没有测试,因为我的电脑现在没有 Visual Studio)

While i < GlinkList.Items.Count
    j = i + 1
    While j < GlinkList.Items.Count
        If GlinkList.Items(j) = GlinkList.Items(i) Then
            GlinkList.Items.Remove(j)
        Else
            j += 1
        End If
    End While
    i += 1
End While

回答by Elan Chindan

I Think I Got the Answer!

我想我得到了答案!

If Not listbox1.Items.Contains("sometext") Then
     Me.listbox1.Items.Add("sometext")
End If

回答by Samir

    Dim i, j As Long
    For i = 0 To ListBox2.Items.Count - 1
        For j = ListBox2.Items.Count - 1 To (i + 1) Step -1
            If ListBox2.Items(i) = ListBox2.Items(j) Then
                ListBox2.Items.Remove(ListBox2.Items(j))
            End If
        Next
    Next

回答by Ojan

I had used distinct method for the following problem but cannot recall how: Create a second listbox2 and make the first hidden then use the following code

我对以下问题使用了不同的方法,但不记得如何:创建第二个 listbox2 并隐藏第一个然后使用以下代码

 Dim i2 As Integer

 For i2 = 0 To ListBox1.Items.Count - 1
     If Not ListBox2.Items.Contains(ListBox1.Items.Item(i2)) Then
         ListBox2.Items.Add(ListBox1.Items.Item(i))
     End If
 Next

Now your second listbox will not have duplicates

现在你的第二个列表框不会有重复