Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 这个列表框在哪里;正在循环中修改的枚举数?_C#_Winforms_Listbox - Fatal编程技术网

C# 这个列表框在哪里;正在循环中修改的枚举数?

C# 这个列表框在哪里;正在循环中修改的枚举数?,c#,winforms,listbox,C#,Winforms,Listbox,下面的代码有效 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]); dg

下面的代码有效

  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;
        }
    }
获取列表框方法如下所示:

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

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


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

只是为了澄清。。它没有在这个函数之外被修改,是吗?您正在使用哪些事件来修改您的列表框?你能用getListBox方法代码更新这个问题吗?你在哪一行得到这个错误?Skeet,我们需要你的时候你在哪里?:-)错误显示在“foreach”行中很可能是
dgView.Columns[item.toString()].Visible=cont
是罪魁祸首,因为它似乎影响了列,从而影响了包含listbox的列元素。
ListBox getListBox()
{
    return columnsForm.Controls.OfType<ListBox>().First() as ListBox;
}
void hideBtn_Click(object sender, EventArgs e)
{
    getListBox().Items.Clear();
    foreach(DataGridViewColumn col in dgView.Columns)
    {
        getListBox().Items.Add(col.Name);
    }
    columnsForm.ShowDialog();
}