[RESOLVED] Error on setting checkstate in a CheckedListBox control
I have a CheckedListBox control that I fill with DataGridView Column HeaderText values. If these columns are visible, I would like to set the CheckedListBox Items to "Checked". My code is as follows:
Code:
For Each col As DataGridViewColumn In frmTimingP2P.dgvOverview.Columns
If col.Visible = True Then
For Each item In clbOverviewColumnOrder.Items
Dim intItemIndex As Integer = clbOverviewColumnOrder.Items.IndexOf(item)
If col.HeaderText = item.ToString Then
clbOverviewColumnOrder.SetItemCheckState(intItemIndex, CheckState.Checked)
End If
Next
End If
Next
Whenever this code runs, I get the following error:
"List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change."
What causes this? How can I get around this issue?
Thanks
Re: Error on setting checkstate in a CheckedListBox control
In this case you cannot use a foreach loop, it's like trying to remove controls using a foreach loop. Instead you have to loop through the items using a for loop and looping them backwards. Take a look at this:
Code:
Dim checked As Boolean = True 'or false
For i As Integer = CheckedListBox1.Items.Count - 1 To 0 Step -1
CheckedListBox1.SetItemChecked(i, checked)
Next
Re: Error on setting checkstate in a CheckedListBox control
looks like it doesnt want you to edit the control while your using the enumerator(thing keeping track of the ForEach/Next loop)
try For/Next loop instead
Re: Error on setting checkstate in a CheckedListBox control
Got it. I revised my code and ended up with the following:
Code:
Dim intCurrentItemIndex As Integer = clbOverviewColumnOrder.Items.Count - 1
Do While intCurrentItemIndex >= 0
Dim strCurrentItem As String = clbOverviewColumnOrder.Items(intCurrentItemIndex)
For Each col As DataGridViewColumn In frmTimingP2P.dgvOverview.Columns
If col.HeaderText = strCurrentItem Then
If col.Visible = True Then
clbOverviewColumnOrder.SetItemCheckState(intCurrentItemIndex, CheckState.Checked)
Else
clbOverviewColumnOrder.SetItemCheckState(intCurrentItemIndex, CheckState.Unchecked)
End If
End If
Next
intCurrentItemIndex -= 1
Loop
It works perfectly. Thanks!
Re: [RESOLVED] Error on setting checkstate in a CheckedListBox control
If I could make a suggestion, don't use a do while in this situation. While it may work, it's quicker to use the for loop I showed above. Pretty much anytime you can use a for loop rather than a do loop, then choose the for loop.
Re: [RESOLVED] Error on setting checkstate in a CheckedListBox control
That is interesting. I was unaware that a For...Next loop was any quicker than a Do...Loop.