ComboBox Cast exception

Posted by: fsegui on 7 May 2020, 3:57 am EST

    • Post Options:
    • Link

    Posted 7 May 2020, 3:57 am EST

    Hello,

    I’m trying the C1ComboBox control. I’m binding datas to the combobox like this:

    cmb.TranslateValue = True
    cmb.ItemsDataSource = comboData
    cmb.ItemsDisplayMember = "DisplayString"
    cmb.ItemsValueMember = "ItemData"
    
    Dim comboData As New BindingSource
    
    comboData.Add(new ComboItem("string1",1)
    comboData.Add(new ComboItem("string2",2)
    ...
    

    When I try to iterate through all items and convert them as ComboItem, I’ve got an InvalidCastException: impossible to convert String to ComboItem:

    For i = 0 To cmb.Items.Count - 1
    	If CType(cmb.Items.Item(i), ComboItem).ItemData = Itemdata Then
    		cmb.SelectedIndex = i
    		Exit Sub
    	End If
    Next i
    

    ComboItem class

    Public Class ComboItem
        Public Property DisplayString As String
        Public Property ItemData As Object
        Public Sub New(displayString As String, Optional itemData As Object = Nothing)
            Me.DisplayString = displayString
            Me.ItemData = itemData
        End Sub
    End Class
    

    How can I get the object and not just the string?

  • Posted 8 May 2020, 4:27 am EST

    Hi Florent,

    The Item property of C1ComboBox returns the ItemsValueMember at associated with particular indexes.

    To get the ComboItem object at a particular index, you need to iterate through the BindingSource object that is assigned as the DataSource of the C1ComboBox as given in code snippet below:

    For i = 0 To comboData.Count - 1
                If CType(comboData.Item(i), ComboItem).ItemData = ItemData Then
                    C1ComboBox1.SelectedIndex = i
                End If
            Next
    

    Regards,

    Prabhat Sharma.

  • Posted 8 May 2020, 7:17 am EST

    Hi,

    Thanks for the details. Works fine like this. Does the text property always returns the itemsdisplaymember ?

  • Posted 11 May 2020, 12:08 am EST

    Hi Florent,

    The Text property of the ComboBox returns the currently selected display member that is shown in the ComboBox editor area.

    Regards,

    Prabhat Sharma.

  • Posted 11 May 2020, 9:14 am EST

    Thanks, that works.

Need extra support?

Upgrade your support plan and get personal unlimited phone support with our customer engagement team

Learn More

Forum Channels