【问题标题】:Where is this ListBox's enumerator being modified in a loop?这个 ListBox 的枚举器在哪里被循环修改?
【发布时间】:2013-09-14 23:24:46
【问题描述】:

下面的代码有效

  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();
}

【问题讨论】:

  • 只是为了澄清......它没有在这个函数之外被修改是吗?
  • 您正在使用哪些事件来修改您的列表框?你能用 getListBox 方法代码更新问题吗?
  • 您在哪一行收到此错误?
  • Skeet,我们需要你的时候你在哪里? :-)
  • “foreach”行中显示错误

标签: c# winforms listbox


【解决方案1】:

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

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

【讨论】:

  • dgView.Columns[item.toString()].Visible = cont; 很可能是罪魁祸首,因为它似乎影响了列,从而影响了包含列表框的列元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 2014-04-07
相关资源
最近更新 更多