سؤال

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.

هل كانت مفيدة؟

المحلول

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)

نصائح أخرى

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]
            }
        }

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(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)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top