我正在尝试将此词典集合绑定到组合框但显示器 是不正确的。 displayMember应该是ProvName,ValueMember应该是键。
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
Dim Country1 As Dictionary(Of String, Province)
Country1 = Module1.CreateCountry
'Display results in combox
ComboBox3.DataSource = New BindingSource(Country1, Nothing)
ComboBox2.DisplayMember = "Value"
ComboBox2.ValueMember = "Key"
End Sub
模块Module1 公共省份作为CollectionBase
Function CreateCountry() As Dictionary(Of String, Province)
Dim Country As New Dictionary(Of String, Province)
Dim Prov As Province
Prov = New Province
With Prov
.Abbrv = "Qc"
.ProvName = "Quebec"
.Population = "7 500 000"
.Region = "East"
End With
Country.Add(Prov.Abbrv, Prov)
Prov = New Province
With Prov
.Abbrv = "BC"
.ProvName = "British Columbia"
.Population = "4 500 000"
.Region = "West"
End With
Country.Add(Prov.Abbrv, Prov)
Prov = New Province
With Prov
.Abbrv = "NS"
.ProvName = "Nova Scotia"
.Population = "2 000 000"
.Region = "Maritimes"
End With
Country.Add(Prov.Abbrv, Prov)
Prov = New Province
With Prov
.Abbrv = "AB"
.ProvName = "Alberta"
.Population = "5 500 000"
.Region = "Prairies"
End With
Country.Add(Prov.Abbrv, Prov)
Return Country
End Function
结束模块
Public Class Province
Public Property Abbrv As String
Public Property ProvName As String
Public Property Population As String
Public Property Region As String
Public Overrides Function ToString() As String
Return ProvName
End Function
End Class
答案 0 :(得分:1)
以下是示例源代码:
'Declare and Fill a generic Dictionary
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add("one", 1)
dictionary.Add("two", 2)
dictionary.Add("three", 3)
dictionary.Add("four", 4)
dictionary.Add("five", 5)
dictionary.Add("six", 6)
dictionary.Add("seven", 7)
dictionary.Add("eight", 8)
'Initialize DisplayMember and ValueMember of an existing combobox to be filled with dictionary values
cboCombo.DisplayMember = "Key"
cboCombo.ValueMember = "Value"
'Bind the combobox to dictionary
cboCombo.DataSource = New BindingSource(dictionary, Nothing)
'Now I can assign the selected value of combobox with this simple command:
cboCombo.SelectedValue = 4
'我还可以使用以下方法检索所选值: value = cboCombo.SelectedValue
如果这有助于您标记为答案
答案 1 :(得分:0)
这只是使用字典将数据绑定到组合框的示例。
声明字典对象并使用以下值对其进行初始化:
Dim dcItems As New Dictionary(Of String, Integer)
lstTPAType.Add("Select", -1)
lstTPAType.Add("Item 1", 0)
lstTPAType.Add("Item 2", 1)
lstTPAType.Add("Item ", 2)
cmbMyCombo.DataSource = New BindingSource(dcItems, Nothing)
cmbMyCombo.ValueMember = "Value"
cmbMyCombo.DisplayMember = "Key"
希望这种通用解决方案能够帮助开发人员寻找它。