Search code examples
vb.netwinformsdata-bindingkeyvaluepair

ComboBox cannot convert from KeyValuePair to Integer


I am getting a DataBinding error where my ComboBox are binded to a KeyValuePair list and the value stored to the DataBase is an integer.

How do I go about converting it?

Here is my code so far:

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

Error

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


Solution

  • Finally resolved the issue by using a custom ComboBox Class. Inside my DTO I created a String property which returns a combined value of ID (Integer) and Description (String).

    Using this property I was able to set the DisplayMember and the ValueMember was set to the ID field which the DataBinding also used. So no casting was required in the end.

    Example:

    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
    

    And after modifying my SetupCombo method.

    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
    

    Finally my 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