2

下面的代码有效

  void selectColumns_Click(object s, EventArgs e)
    {
        ListBox lBx = getListBox();
        for (int i = 0; i < lBx.Items.Count-1;i++ )
        {
            bool contained = lBx.SelectedItems.Contains(lBx.Items[i]);
            dgView.Columns[lBx.Items[i].ToString()].Visible = contained;
        }
    }

但这不起作用-抛出错误 “此枚举器绑定到的列表已被修改。仅当列表未更改时才能使用枚举器。”

  void selectColumns_Click(object s, EventArgs e)
    {
        ListBox lBx = getListBox();
        foreach (var item in lBx.Items )
        {
            bool cont = lBx.SelectedItems.Contains(item);
            dgView.Columns[item.toString()].Visible = cont;
        }
    }

获取 ListBox 方法如下:

ListBox getListBox()
{
    return columnsForm.Controls.OfType<ListBox>().First() as ListBox;
}

还通过单击 hideColumnsButton 填充列表框

void hideBtn_Click(object sender, EventArgs e)
{
    getListBox().Items.Clear();
    foreach(DataGridViewColumn col in dgView.Columns)
    {
        getListBox().Items.Add(col.Name);
    }
    columnsForm.ShowDialog();
}
4

1 回答 1

0

您的代码中没有任何内容明确尝试修改枚举循环中的列表。调用SelectedItems只是为您提供对基础选定项目的引用列表,不会修改列表本身。

所以我能看到的唯一可能性是有另一个执行线程(或一些你没有向我们展示的代码)正在修改该循环范围之外的列表。

于 2013-09-11T04:37:45.867 回答