Search code examples
vb.netcomboboxcheckedlistbox

How to adding checked item from checkedlistbox to combobox


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...


Solution

  • Oddly enough the CheckedListBox has a CheckedItems property, which is a collection. As such you can loop through it like you can any other collection, using a For or For Each loop.

    then, Each item needs to be added to the Items collection of the ComboBox.

    like this sample:

    Public Class frmCheckedListBox
    
    Private Sub frmCheckedListBox_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.CheckedListBox1.Items.Clear()
        Me.CheckedListBox1.BeginUpdate()
        Me.CheckedListBox1.Items.Add("One")
        Me.CheckedListBox1.Items.Add("Two")
        Me.CheckedListBox1.Items.Add("Three")
        Me.CheckedListBox1.Items.Add("Four")
        Me.CheckedListBox1.Items.Add("Five")
        Me.CheckedListBox1.EndUpdate()
    End Sub
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For Each Item As String In Me.CheckedListBox1.CheckedItems
            Me.ComboBox1.Items.Add(Item)
            Me.ComboBox1.SelectedIndex = 0
        Next
    End Sub
    

    End Class

    As sample code shows, the CheckedItems collection contains the items that are checked, just as the name suggests. It doesn't contain a Boolean value for each an every item to indicate whether it is checked or not. If an item is checked then that item is in the CheckedItems, and if it isn't then it isn't. You simply need to loop through the collection and get every item in it, because it contains all the items that are checked and none that aren't.

    in the end you can put :

    Me.Combobox1.items.clear()
    

    because when it would click with sample code it would have the one that clicked then on the next click would return the previous one it had clicked and then the new one all compiled in the combobox selection menu

    perhaps my answer can help you solve your problems