VB中IndexOf始终返回0:ListBox元素无法正常移除求助
嘿,这个问题我一眼就看出症结所在啦!你代码里的移除方法用错了,这才导致明明找到索引却删不掉项。
核心问题:用错了移除方法
ListBox.Items的Remove()方法是用来移除指定对象的,而如果你想通过索引位置删除项,得用RemoveAt()方法!你现在写的ListBox1.Items.Remove(index),VB.NET会把这个index整数当成要查找的对象去匹配,而不是把它当作索引位置——这就相当于你告诉程序“帮我删掉值为X的项”,但ListBox里根本没有这个整数X,自然啥也删不掉。
修正后的代码
直接把移除那行改成RemoveAt(index)就搞定了,再给你加个小保险(确认索引有效),顺便去掉字符串前后空格避免意外:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim str As String = TextBox1.Text.Trim() ' 去除前后空格,避免因空格导致的匹配失败 If ListBox1.Items.Contains(str) Then Dim index As Integer = ListBox1.Items.IndexOf(str) If index <> -1 Then ' 保险起见,确认确实找到了有效索引 ListBox1.Items.RemoveAt(index) End If End If ListBox1.Items.Add(str) End Sub
额外补充:处理大小写/空格不敏感的场景
如果你的需求是忽略大小写(比如输入"Test"和ListBox里的"test"要视为同一个项),那默认的Contains和IndexOf可能不好用,因为它们是区分大小写的。这时候可以自己循环查找:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim str As String = TextBox1.Text.Trim() Dim targetIndex As Integer = -1 ' 循环遍历所有项,不区分大小写匹配 For i As Integer = 0 To ListBox1.Items.Count - 1 If String.Equals(ListBox1.Items(i).ToString(), str, StringComparison.OrdinalIgnoreCase) Then targetIndex = i Exit For ' 找到就退出循环 End If Next If targetIndex <> -1 Then ListBox1.Items.RemoveAt(targetIndex) End If ListBox1.Items.Add(str) End Sub
这样不管大小写是否一致,都能正确找到并移除旧项啦!
内容的提问来源于stack exchange,提问作者Jordan Gray
相关产品推荐
相关产品推荐

