我遇到了一个问题,我试图从字典中的列表框中选定索引处删除一个元素。我在SortedDictionary
中添加了3个元素,并将它们打印到列表框中。我正在尝试从列表框中突出显示的字典中删除该项目,但是当我单击“删除”时,我的System.ArgumentNullException: 'Value cannot be null. Parameter name: key'
子中就会出现btnDeleteLibrary_Click
,为什么?
错误发生在第Libraries.Remove(lstLibraries.SelectedValue)
行
Public Class frmManager
Dim Libraries As New SortedDictionary(Of String, String)
Private Sub frmManager_Load(sender As Object, e As EventArgs) Handles Me.Load
Libraries.Add("Zahnow Library", "SVSU")
Libraries.Add("Fleschner Memorial Library", "BR")
Libraries.Add("Scott D. James Technical Repository", "SDJ")
lstLibraries.Items.Clear()
populatelstLibrary()
End Sub
Sub populatelstLibrary()
For Each library In Libraries
lstLibraries.Items.Add(vbCrLf & library.Key & " --- " & library.Value)
Next
End Sub
Private Sub btnDeleteLibrary_Click(sender As Object, e As EventArgs) Handles btnDeleteLibrary.Click
Libraries.Remove(lstLibraries.SelectedValue)
lstLibraries.Items.Clear()
populatelstLibrary()
End Sub
End Class
答案 0 :(得分:1)
由于要为ListBox项构造自定义显示字符串,因此将其直接映射到字典变得更加困难。
最简单的解决方案是创建一个存储在ListBox中的自定义类,并设置ListBox的DisplayMember
和ValueMember
属性,告诉它如何显示每个项目以及应显示的属性致电SelectedValue
时从物品中获取物品。
班级:
Public Class LibraryItem
Public Property Name As String
Public Property Code As String
Public ReadOnly Property DisplayName As String
Get
Return vbCrLf & Me.Name & " --- " & Me.Code
End Get
End Property
Public Sub New()
End Sub
Public Sub New(ByVal Name As String, ByVal Code As String)
Me.Name = Name
Me.Code = Code
End Sub
End Class
初始设置:
Private Sub frmManager_Load(sender As Object, e As EventArgs) Handles Me.Load
'Tell the ListBox which properties to use for display and value.
lstLibraries.DisplayMember = "DisplayName"
lstLibraries.ValueMember = "Name"
'Your code...
End Sub
填充列表框:
Sub populatelstLibrary()
For Each library In Libraries
lstLibraries.Items.Add(New LibraryItem(library.Key, library.Value))
Next
End Sub
现在SelectedValue
将为您提供所选项目的Name
属性的值,该属性与字典中的键相对应。
答案 1 :(得分:1)
我会更改您代码中的某些内容。首先,您似乎已经用“键和值”的错误值构建了已排序的字典,将其更改为
Libraries.Add("SVSU","Zahnow Library")
Libraries.Add("BR", "Fleschner Memorial Library")
Libraries.Add("SDJ", "Scott D. James Technical Repository")
' and call immediately
populatelstLibrary()
现在populatelstLibrary中将代码更改为
Sub populatelstLibrary()
lstLibraries.DataSource = Nothing
lstLibraries.DisplayMember = "Value"
lstLibraries.ValueMember = "Key"
lstLibraries.DataSource = Libraries.ToList()
End Sub
最后,在按钮中单击,只需检查是否为空并删除SelectedValue
Private Sub btnDeleteLibrary_Click(sender As Object, e As EventArgs) Handles btnDeleteLibrary.Click
If lstLibraries.SelectedValue IsNot Nothing Then
Libraries.Remove(lstLibraries.SelectedValue)
populatelstLibrary()
End If
End Sub