Search code examples
c#.netlistcheckedlistbox

Getting Label Text of CheckBox from a CheckedListBox


I currently have a CheckedListBox with several boxes. I want to be able to test every Checkbox in the list to see if it's checked, and if it is, add it's text value (CheckBox.Text) to a List of strings.

Here is what I have:

for ( int i = 0; i < multiTaskChecks.Items.Count; i++ )
{
    if ( multiTaskChecks.GetItemChecked(i) )
    {
        checkedMultiTasks.Add(multiTaskChecks.GetItemText(i));
    }
}

Using this, GetItemText is returning 0, 1, 2, 3, etc instead of the text values that I'm after. I have also tried CheckedListBox.Text.IndexOf(i), CheckedListBox.Text.ToList(), each without any luck.

I just cannot get the label text of one of these CheckBoxes from the CheckedListBox. Any help with this would be really appreciated.


Solution

  • Firstly, you should be able to loop through the checked items only like so

    foreach (var item in multiTaskChecks.CheckedItems)
    {
    }
    

    then depending on the type of the item, get whatever property you want from it. Sounds like it is just a Text or you just want the string, so

    foreach (var item in multiTaskChecks.CheckedItems)
    {
        checkedMultiTasks.Add(item.ToString());
    }
    

    or I prefer

    checkedMultiTasks.AddRange(multiTaskChecks.CheckedItems.
        OfType<object>().Select(‌​i => i.ToString()));