使用字典作为组合框数据源

Mar*_*tin 2 vb.net combobox dictionary

我想从字典源填充组合框。该字典有一个类值,我想将类属性用于组合框值。

示例类

Public Class Customer
    Public ID As Integer
    Public Name As String
    Public Address As String
    Public City As String

    Public Sub New(ByVal newID As Integer, ByVal newName As String, ByVal newAddress As String, ByVal newCity As String)
        ID = newID
        Name = newName
        Address = newAddress
        City = newCity
    End Sub
End Class
Run Code Online (Sandbox Code Playgroud)

表格示例

Public Class Form1
    Dim Customers As New Dictionary(Of Integer, Customer)

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Customers.Add(341, New Customer(341, "Michael", "Street 52", "New York"))
        Customers.Add(149, New Customer(149, "Susan", "Street 12", "Los Angelos"))
        Customers.Add(721, New Customer(721, "Bill", "Street 98", "Houston"))
        Customers.Add(958, New Customer(958, "Jeff", "Street 54", "Washington"))

        ComboBox1.DataSource = Customers 'What to use as a datasource??
        ComboBox1.DisplayMember = "Name"
        ComboBox1.ValueMember = "ID"
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        MsgBox(ComboBox1.SelectedValue)
    End Sub
End Class
Run Code Online (Sandbox Code Playgroud)

如何设置 ComboBox1 属性,以便我可以看到客户名称为DisplayMember,其 ID 为ValueMember

Ňɏs*_*arp 5

当绑定到 a 时Dictionary,事情变得有点……“间接”。

与 a 不同List(Of T),字典没有用作 a 所需的接口DataSource。为此,您需要使用一个BindingSource.

' NVP is a NameValuePair class I had on hand
Private NamedPairs As New Dictionary(Of Integer, NVP)
...
NamedPairs.Add(341, New NVP("Michael", 341))
NamedPairs.Add(149, New NVP("Susan", 149))
NamedPairs.Add(721, New NVP("Bill", 721))
NamedPairs.Add(958, New NVP("Jeff", 958))

ComboBox1.DataSource = New BindingSource(NamedPairs, Nothing)
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "Key"
Run Code Online (Sandbox Code Playgroud)

与列表不同的是,列表中有Customer项目,字典内部是一组KeyValuePair(Of TK, TV). 这就是您使用DisplayMemberValueMember属性的内容。

最后一步可能是更改您的Customer类以控制显示内容。由于您无法映射到实际/特定Customer属性,因此默认显示可能类似于WindowsApp17.Foo.Customer. 要显示更有价值的内容,您需要覆盖ToString()

Class Customer
    ...
    Public Overrides Function ToString() As String
        Return Name
    End Function
Run Code Online (Sandbox Code Playgroud)

你可以让它显示你想要的任何内容:

Return String.Format("{0} ({1})", Name, Value.ToString)
' or
Return String.Format("{0} from ({1})", FirstName, City)

Private Sub ComboBox1_SelectedIndexChanged(sender ...
    Console.WriteLine("SelectedValue: {0}  ", ComboBox1.SelectedValue)
End Sub
Run Code Online (Sandbox Code Playgroud)

输出:

选定值:721

SelectedItem整个 KVP 将为Object,因此将其投射回来:

Dim kvp As KeyValuePair(Of Int32, Customer) = CType(cbo1.SelectedItem,
                 KeyValuePair(Of Int32, Customer))
Dim thisCust As Customer = kvp.Value
Run Code Online (Sandbox Code Playgroud)