【问题标题】:ComboBox cannot convert from KeyValuePair to IntegerComboBox 无法从 KeyValuePair 转换为 Integer
【发布时间】:2019-12-01 12:31:51
【问题描述】:

我收到一个 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

错误

测试:Value[1, TestValue] 无法转换为类型“ID”

【问题讨论】:

  • 为什么不使用_ListTable 中的内容(不清楚数据的来源是什么)作为BindingSource 的DataSource?因此,您可以在设置DisplayMember 和绑定时直接使用字段名称。看起来你让它变得比它需要的更复杂。

标签: vb.net winforms data-binding keyvaluepair


【解决方案1】:

应该不会吧

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

相反,当您添加 KeyValuePairs 时?

【讨论】:

  • 是的,但是当我设置DataBindings 时如何指定Key
  • 我几乎不使用BindingSource,你不能设置comboBox1.DataSource = comboSource吗?
【解决方案2】:

最终通过使用自定义组合框Class 解决了这个问题。在我的 DTO 中,我创建了一个 String 属性,它返回 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

最后是我的数据绑定

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

【讨论】:

    猜你喜欢
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多