【问题标题】:How to search a listbox (bound to a dictionary) through a text field如何通过文本字段搜索列表框(绑定到字典)
【发布时间】:2021-12-18 14:15:53
【问题描述】:

我想知道是否有人可以帮助我理解字典以及解除绑定时会发生什么。

我有一个包含许多音乐曲目的列表框,这些曲目是从文件中读取的。文件信息是 mp3 音乐文件的位置。数据分为 2 个值。歌曲标题和歌曲位置。这些作为键和值存储在我的 MusicDictionary 中,一切正常。

我现在希望能够通过文本字段在列表框中搜索最喜欢的歌曲,并希望列表框显示找到的项目(如果有)。据我了解,到目前为止,我必须取消绑定列表框并创建一个新的列表框以显示找到的项目。

到目前为止,根据下面的代码,我遇到了很多错误

System.ArgumentException: '设置 DataSource 属性时无法修改项目集合。'

这是我想弄清楚的代码

Private Sub TextBoxSearchMusic_TextChanged(sender As Object, e As EventArgs) Handles TextBoxSearchMusic.TextChanged
    'ListBox1.Items.Clear()
    For Each item As String In MusicDictionary.Keys
        If item.StartsWith(TextBoxSearchMusic.Text, StringComparison.CurrentCultureIgnoreCase) Then
            ListBox1.Items.Add(item)
        End If
        ListBox1.DataSource = ListBox1.Items
    Next
End Sub

如果有人能找出我做错了什么,我将不胜感激。

所以,问题是我是否从列表框中取消绑定音乐词典数据源并为列表框创建一个新的临时创建项以显示。我会丢失原始数据吗?如果不能,我可以再次绑定吗?

谢谢

(编辑)

我已经设法让代码停止崩溃,但我的列表框没有被填充,这是我更新的代码。

       ListBox1.DataSource = Nothing
    
    ListBox1.Items.Clear()

    For Each item As String In allItems
        If item.Contains(TextBoxSearchMusic.Text) Then
            ListBox1.Items.Add(item)
        End If
    Next
    ListBox1.DataSource = ListBox1.Items
    'ListBox1.DisplayMember.

【问题讨论】:

    标签: .net dictionary listbox


    【解决方案1】:

    这花费的时间比我想象的要长,但我设法解决了这个问题。

    ListBox1.DataSource = Nothing 'Unbinds the existing datasource
            ListBox1.Items.Clear() 'Clears the listbox of any content
            Dim newDictionary = MusicDictionary.Where(Function(pair) pair.Key.Contains(TextBoxSearchMusic.Text)).ToDictionary(Function(pair) pair.Key, Function(pair) pair.Value) 'Filters the Music Dictionary through the TextBoxSearchMusic field and adds the result to the newDictionary 
            For i = 0 To newDictionary .Count - 1 'Loop through the newDictionary 
                ListBox1.Items.Add(newDictionary.Keys(i) & newDictionary.Values(i))  'Adds all the found Items to the newDictionary 
            Next
            ListBox1.DataSource = New BindingSource(newDictionary, Nothing) 'Binds the newDictionary to the listbox
            ListBox1.DisplayMember = "Key" 'Displays only the Key in the listbox
    

    我希望以上内容能够在将来对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-03-29
      • 1970-01-01
      • 2016-08-28
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多