Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through checkedListBox testing for checked - cast error

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.

like image 908
topofsteel Avatar asked Feb 14 '13 10:02

topofsteel


3 Answers

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)

like image 143
Steve Avatar answered Sep 22 '22 17:09

Steve


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]
            }
        }
like image 29
VladL Avatar answered Sep 21 '22 17:09

VladL


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)

like image 23
pramod gehlot Avatar answered Sep 22 '22 17:09

pramod gehlot