VB.Net:如何将字典集合绑定到组合框? [英] VB.Net : How do you bind a dictionary collection to a Combobox?
本文介绍了VB.Net:如何将字典集合绑定到组合框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将此字典集合绑定到组合框,但显示是不正确的.displayMember 应该是 ProvName,ValueMember 应该是键.
I am trying to bind this dictionary collection to a combobox but the display is not correct. The displayMember should be the ProvName and the ValueMember should be the key.
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公共省份作为收藏库
Module Module1 Public provinces As 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
推荐答案
示例源代码如下:
'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
'我还可以通过以下方式检索选定的值:值 = cboCombo.SelectedValue
'I can also retrive the selected value with: value = cboCombo.SelectedValue
如果这有助于您标记为答案
If this help you mark as answer
这篇关于VB.Net:如何将字典集合绑定到组合框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文