iterate through checkedListBox testing for checked - cast error

topofsteel picture topofsteel · Feb 14, 2013 · Viewed 13.4k times · Source

i'm trying to check each item in a checkedlistbox and do something with the item depending if it is checked or not. I've been able to just get the checked items with the indexCollection, but i'm having trouble getting all of the items, i'm getting this error 'Unable to cast object of type 'System.String' to type 'System.Windows.Forms.ListViewItem'

        foreach (ListViewItem item in checkedListBox2.Items)
        {
            if (item.Checked == true)
                //do something with item.name

            else
                //do something else with item.name
        }

i'm unsure why it's giving me the string cast error in the foreach line. How can I accomplish this? Thanks.

Answer

Steve picture Steve · Feb 14, 2013

If you allow a checkbox to have the Indeterminate state then you should use the GetItemCheckState method to retrieve the state of a check box

for (int i = 0; i < checkedListBox2.Items.Count; i++) 
{
     CheckState st = checkedListBox2.GetItemCheckState(checkedListBox2.Items.IndexOf(i));
     if(st == CheckState.Checked)
        ....
     else if(st == CheckState.Unchecked)
        ....
     else
        ... // inderminate
}        

otherwise is enough to call GetItemChecked that return a true/false value (true also for the indeterminate state)