gpt4 book ai didi

vb.net - 使用字典作为组合框数据源

转载 作者:行者123 更新时间:2023-12-03 09:19:52 24 4
gpt4 key购买 nike

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

示例类

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

表格示例

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

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

最佳答案

当绑定(bind)到字典时,事情变得有点......“间接”。

List(Of T)不同,字典不具有用作数据源所需的接口(interface)。为此,您需要使用 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"

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

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

Class Customer
...
Public Overrides Function ToString() As String
Return Name
End Function

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

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

输出:

SelectedValue: 721

SelectedItem 会将整个 KVP 作为 Object,因此将其转换回来:

Dim kvp As KeyValuePair(Of Int32, Customer) = CType(cbo1.SelectedItem,
KeyValuePair(Of Int32, Customer))
Dim thisCust As Customer = kvp.Value

关于vb.net - 使用字典作为组合框数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33608205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com