2
votes

The code below works

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

but this does not work- throws error "List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change."

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

Get ListBox method is below:

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

also the listbox is getting populated by clicking on a hideColumnsButton

void hideBtn_Click(object sender, EventArgs e)
{
    getListBox().Items.Clear();
    foreach(DataGridViewColumn col in dgView.Columns)
    {
        getListBox().Items.Add(col.Name);
    }
    columnsForm.ShowDialog();
}
1
Just to clarify.. it's not being modified outside of this function is it? - Simon Whitehead
which events are you using modify your listbox? can you update the question with getListBox method code? - Damith
On which line you are getting this error ? - Ronak Patel
Skeet, where are you when we need you? :-) - paxdiablo
error shows in the "foreach" line - Pete_ch

1 Answers

0
votes

There's nothing in your code which explicitly tries to modify the list within the enumeration loop. Calling SelectedItems simply gives you a list of references to the underlying selected items, ot does not modify the list itself.

So the only possibility I can see is that there's another thread of execution (or some code you're not showing us) which is modifying the list outside the scope of that loop.