user3191666
user3191666

Reputation: 159

Get the text from a check box list

I have a check box list in a winform.

If the check box list is selected then I want the value to be passed into a string:

For i As Integer = 0 To cbxlstPancakes.Items.Count - 1
    If cbxlstPancakes.GetItemChecked(i) Then

        Dim currentPancake As String = cbxlstPancakes.SelectedItem.ToString

    Else
        'do something if they are not checked.
    End If
Next

Upvotes: 0

Views: 5552

Answers (1)

SnookerC
SnookerC

Reputation: 170

Now I'm confused if you're using strings vs. a bound datasource. For the datasource, give one of these a try.

If you only care about CHECKED items, it's a little easier:

    '=== IF you only care about the checked items (assuming you used a databound control)
    For Each dr As DataRowView In cbxlstPancakes.CheckedItems
        Dim currentPancake As String = dr.Item(0)   '--> TODO:  correct column from your datasource
        MessageBox.Show(currentPancake)
    Next

IF you care about both checked AND unchecked items, you should be able to access them this way (should work for EITHER bound or unbound):

    '=== IF you care about both checked and unchecked items
    For i As Integer = 0 To cbxlstPancakes.Items.Count - 1
        If cbxlstPancakes.GetItemChecked(i) Then
            MessageBox.Show(cbxlstPancakes.GetItemText(cbxlstPancakes.Items(i)))
        Else
            'Do something if they're not checked
        End If
    Next

I'm not sure why the CheckedListBox was implemented a little differently than some other controls (with the .Getxxxxx() methods, etc.). But this seems to work for me!

Upvotes: 3

Related Questions