Search code examples
c#winformscheckedlistbox

Why is the ItemText of my CheckedListBox viewed as being "0"?


With this code:

for (int i = 0; i <= (checkedListBoxPlatypi.Items.Count - 1); i++)
{
    if (checkedListBoxPlatypi.GetItemCheckState(i) == CheckState.Checked)
    {
        ReturnListPlatypi.Add(ParsePlatypusID(checkedListBoxPlatypi.GetItemText(i)));
    }
}

...and a CheckedListBox that does have text assigned to it via (FriendlyPlatypus is a string with content):

checkedListBoxPlatypi.Items.Add(FriendlyPlatypus);

...ParsePlatypusID() is being passed "0"...???


Solution

  • I'm assuming you didn't add "i" to the listbox, so there wouldn't be any text for that object. You just need the object directly:

    for (int i = 0; i <= (checkedListBoxPlatypi.Items.Count - 1); i++)
    {
        if (checkedListBoxPlatypi.GetItemCheckState(i) == CheckState.Checked)
        {
            ReturnListPlatypi.Add(ParsePlatypusID(checkedListBoxPlatypi.Items[i].ToString()));
        }
    }
    

    If, in fact, you had added an object through a databinding, and you wanted to get directly to the "DisplayMember" field, you would use:

    for (int i = 0; i <= (checkedListBoxPlatypi.Items.Count - 1); i++)
    {
        if (checkedListBoxPlatypi.GetItemCheckState(i) == CheckState.Checked)
        {
            ReturnListPlatypi.Add(ParsePlatypusID(checkedListBoxPlatypi.GetItemText( checkedListBoxPlatypi.Items[i])));
        }
    }