VB.Net:如何将字典集合绑定到组合框



我正在尝试将此字典集合绑定到组合框,但显示不正确。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

模块模块1 公共省份作为收集基地

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

'我还可以使用以下命令检索所选值: value = cboCombo.SelectedValue

如果这有助于您将答案标记为答案

这只是使用字典将数据绑定到组合框的示例。

声明字典对象并使用值对其进行初始化,如下所示:

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"

希望这个通用解决方案能帮助开发人员寻找它。

最新更新