在CheckedListBox控件中设置checkstate时出错?

时间:2013-02-22 18:24:49

标签: vb.net datagridview checkedlistbox

我有一个CheckedListBox控件,我用DataGridView Column HeaderText值填充。如果这些列可见,我想将CheckedListBox项设置为“已检查”。我的代码如下:

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

每当此代码运行时,我都会收到以下错误:

“此枚举器绑定的列表已被修改。只有列表不更改时才能使用枚举器。”

是什么原因引起的?我怎样才能解决这个问题?

由于

2 个答案:

答案 0 :(得分:1)

每当通过枚举器执行for循环时,枚举都无法修改或抛出此异常。

我不确定为什么枚举会在这里发生变化(代码的某些其他部分可能会对检查状态的变化作出反应)但是解决这个问题的一种方法是实例化一个枚举器和然后循环通过它。

我不知道VB,所以这里有一些伪代码!

e.g。

newEnumerator = ColumnOrder.Items.GetEnumerator()

begin loop through newEnumerator
   set checkbox
end loop

因此,即使Items列表发生更改,也不应影响此枚举器。

答案 1 :(得分:0)

感谢您的建议。我猜这个错误与以下事实有关:在某些情况下,你不能在For ... Next循环中修改一组控件。

我修改了我的代码并最终得到以下内容:

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
相关问题