2

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();
}
Pete_ch
  • 1,301
  • 2
  • 28
  • 39

1 Answers1

0

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • It's likely that `dgView.Columns[item.toString()].Visible = cont;` is the culprit as it appears to be affecting the column and thus the column elements that contain the listbox. – Brad Rem Sep 11 '13 at 12:50