How to adding checked item from checkedlistbox to combobox

Flashidkz picture Flashidkz · Dec 24, 2011 · Viewed 20.1k times · Source

I want to adding checked item from checkedlistbox to my combobox, but i have a little problem here. Combobox only show 1 item last checked. This is my sample code.

    If CheckedListBox1.CheckedItems.Count <> 0 Then
        For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
            cbCheckedItem.Text = CheckedListBox1.CheckedItems(i).ToString
        Next i
    End If

anyone can help me show all checked item?? thank's for your help...

Answer

Cody Gray picture Cody Gray · Dec 24, 2011

You aren't adding the items to the combo box, you're only setting its Text property. That's only changing the text currently displayed in the combo box, and only one item can be displayed at a time.

If you want the items to be permanent and selectable, you need to add them to the combo box control's Items collection.

Sample code:

If CheckedListBox1.CheckedItems.Count > 0 Then
    For Each checkedItem In CheckedListBox1.CheckedItems
        cbCheckedItem.Items.Add(checkedItem.ToString())
    Next
End If

Or, better yet, use the AddRange method:

If CheckedListBox1.CheckedItems.Count > 0 Then
    Dim checkedItems() As String = CheckedListBox1.CheckedItems.Cast(Of String).ToArray()
    cbCheckedItems.Items.AddRange(checkedItems)
End If