从拆分列表中搜索字符串

时间:2015-11-05 08:17:36

标签: vb.net

尝试从列表框中拆分和存储字符串并搜索然后搜索我存储它们的文本文件的内容,希望将它们分类到不同的类别中,

首先,我得到一个"对象引用未设置为对象的实例。"这个错误

        Dim variable As String = Nothing
    If listArray.SelectedIndex > 0 Then
        variable = listArray.Items(listArray.SelectedIndex)
    End If
    Dim part As String() = variable.Split(New Char() {","c})
    Dim line As String
    For Each line In part
        MessageBox.Show(line)

其次,这是用于搜索这些分离字符串的正确代码吗?

 For count As Integer = 0 To Logbook.listArray.Items.Count - 1
        Dim searchIndex As String = Logbook.listArray.Items(count).ToString
        If searchIndex.Contains(indexSearch.Text) Then
            Logbook.listArray.SetSelected(0, True)
        End If
    Next

我对StackOverflow很陌生,如果我不及时了解网站礼仪,我表示歉意。

1 个答案:

答案 0 :(得分:0)

  

我得到一个"对象引用未设置为对象的实例。"

我猜你不知道第一项是在索引0,如果没有选择项目,SelectedIndex会返回-1。这就是为什么以下代码抛出异常的原因:

Dim variable As String = Nothing
If listArray.SelectedIndex > 0 Then
    variable = listArray.Items(listArray.SelectedIndex)
End If
Dim part As String() = variable.Split(New Char() {","c}) ' <--- variable Nothing if first item selected

然后您只需使用<> -1>= 0

Dim variable As String = Nothing
If listArray.SelectedIndex >= 0 Then
    variable = listArray.Items(listArray.SelectedIndex)
End If

根据问题的第二部分(总是只询问一次),您还没有提供足够的信息来了解您想要什么以及什么不能与您的代码一起使用。