iterate through checkedListBox testing for checked - cast error
Asked Answered
V

2

7

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.

Valvate answered 14/2, 2013 at 10:22 Comment(0)
L
7

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)

Lavoisier answered 14/2, 2013 at 10:40 Comment(0)
Z
2

CheckedListBox.Items holds the collection of objects, not the collection of ListViewItem

You can check it this way

        for (int i = 0; i < checkedListBox2.Items.Count; i++)
        {
            if (checkedListBox2.GetItemChecked(i))
            {
                //do something with checkedListBox2.Items[i]
            }
            else
            {
                //do something else with checkedListBox2.Items[i]
            }
        }
Zumwalt answered 14/2, 2013 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.