Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I loop through a CheckedList

Status
Not open for further replies.

tshad

Programmer
Jul 15, 2004
386
US
How do I loop through a CheckedListBox and look at the name and if the name is in a string, check it.

I can figure out how to get the name:

foreach (var item in chkSelectStatementColumns.Items)
{
if (lbStatementNames.Text.IndexOf(item.ToString()) != -1)
{
MessageBox.Show(item.ToString());
}
}

But how do I check it?

I can check it using a for loop but how to I get the text?

I can't seem to figure out how to do both: get the text of the checkbox and then check or uncheck it.

Thanks,

Tom
 
I thought I figured it out but it doesn't work. If you change the state of any of the checkboxes, you get an error:

Code:
            ktr = 0;

            foreach (var item in chkSelectStatementColumns.Items)
            {
                if (txtSelectStatement.Text.IndexOf(item.ToString()) != -1)
                {
                    chkSelectStatementColumns.SetItemCheckState(ktr, CheckState.Checked);
                    //MessageBox.Show(item.ToString());
                }
                ktr++;
            }

When I change any of the items to checked, it gives me an error:

List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

I can understand if I had added or deleted an item why would changing the value do it.

How do I get this to work?

Thanks,

Tom
 
I figured it out.

Code:
for (int i = 0; i < chkSelectStatementColumns.Items.Count; i++)
{
    if (txtSelectStatement.Text.IndexOf(chkSelectStatementColumns.Items[i].ToString()) != -1)
    {
        chkSelectStatementColumns.SetItemCheckState(i, CheckState.Checked);
    }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top