سؤال

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:

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

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

المحلول 2

Thanks for the advice. I guess the error was related the the fact that, under some circumstances, you cannot modify a set of controls during a For...Next loop.

I have revised my code and ended up with the following:

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

نصائح أخرى

Whenever are doing a for loop through an enumerator, the enumeration can't be modified or it throws this exception.

I'm not certain exactly why the enumeration would be changing here (it could be possible some other parts of your code are reacting to the change in check state) but one way to get around this would be to instantiate an enumerator and then loop through that instead.

I don't know VB, so here's some psuedo code!

e.g.

newEnumerator = ColumnOrder.Items.GetEnumerator()

begin loop through newEnumerator
   set checkbox
end loop

So even if the Items list changes, it shouldn't affect this enumerator.

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