ComboBox 无法从 KeyValuePair 转换为 Integer

ComboBox cannot convert from KeyValuePair to Integer

我收到一个 DataBinding 错误,其中我的 ComboBox 绑定到 KeyValuePair 列表并且存储到 DataBase 的值是一个整数。

我该如何转换它?

到目前为止,这是我的代码:

Private Sub SetupeCombo()
     Dim comboSource = New List(Of KeyValuePair(Of Integer, String))

     For Each o In _List
          comboSource.Add(New KeyValuePair(Of Integer,String)(o.ID, o.Details))
     Next

     comboBox1.DisplayMember = NameOf(Table.Details)
     comboBox1.ValueMember =  NameOf(Table.ID)
     comboBox1.DataSource = New BindingSource(comboSource, Nothing)
End Sub
Public Sub BindComboBox()
     Dim comboBoxBindings = comboBox1.DataBindings.Add(NameOf(ComboBox.SelectedValue), dataSource, NameOf(dataSource.ID), True, DataSourceUpdateMode.OnPropertyChanged, String.Empty)        
     AddHandler comboBoxBindings.BindingComplete, AddressOf comboBoxBindings _BindingComplete
End Sub
Private Sub comboBoxBindings_BindingComplete(ByVal sender As Object, ByVal e As BindingCompleteEventArgs)
      If e.BindingCompleteState <> BindingCompleteState.Success Then MessageBox.Show("Test: " & e.ErrorText)
End Sub

错误

Test: Value[1, TestValue] cannot be converted to a type 'ID'

不应该是

comboBox1.DisplayMember = "Value"
comboBox1.ValueMember =  "Key"

相反,当您添加键值对时?

最终使用自定义 ComboBox Class 解决了问题。在我的 DTO 中,我创建了一个 String 属性,其中 returns 是 ID(整数)和描述(字符串)的组合值。

使用这个 属性 我能够设置 DisplayMember 并且 ValueMember 被设置为 DataBinding 也使用的 ID 字段。所以最后不需要铸造。

示例:

Public Class ComboBox
    Public Property Details As String
    Public Property ID As Integer
    Public ReadOnly Property Display() As String
        Get 
            Return $"{ID}: {Details}"
        End Get
    End Property
End Class

并且在修改我的SetupCombo方法之后。

Private Sub SetupeCombo()
     Dim comboSource = _list.Select(Function(x) New CombBox With{
                                  .ID = x.ID, 
                                  .Details = x.Details})
                            .ToList()   

     comboBox1.DisplayMember = NameOf(ComboBox.Display)
     comboBox1.ValueMember =  NameOf(ComboBox.ID)
     comboBox1.DataSource = comboSource
End Sub

最后是我的 DataBinding

Public Sub BindComboBox()
     Dim comboBoxBindings = comboBox1.DataBindings.Add(NameOf(ComboBox.SelectedValue), dataSource, NameOf(ComboBox.ID), True, DataSourceUpdateMode.OnPropertyChanged, String.Empty)        
     AddHandler comboBoxBindings.BindingComplete, AddressOf comboBoxBindings _BindingComplete
End Sub