C# 获取错误:集合已修改;枚举操作可能无法执行,如何在列表框上设置所选索引?
我使用以下代码选择列表框中的下一个列表项或第一个列表项:C# 获取错误:集合已修改;枚举操作可能无法执行,如何在列表框上设置所选索引?,c#,listbox,C#,Listbox,我使用以下代码选择列表框中的下一个列表项或第一个列表项: if (ListBox.SelectedIndex == lst.Count - 1) ListBox.SelectedIndex = 0; else this.ListBox.SelectedIndex = ListBox.SelectedIndex + 1; 它正在抛出异常: Collection was modified; enumeration operation may not execute 修改集合的原因
if (ListBox.SelectedIndex == lst.Count - 1)
ListBox.SelectedIndex = 0;
else
this.ListBox.SelectedIndex = ListBox.SelectedIndex + 1;
它正在抛出异常:
Collection was modified; enumeration operation may not execute
修改集合的原因是我需要修改其中一个列表项的内容。我找到需要修改的列表项,在该索引处删除它,然后在同一索引处重新添加它
是否有办法修改列表框的内容并仍然能够设置SelectedIndex?这可能取决于执行顺序以及读取和写入属性的时间 尝试: 请尝试以下方法:
var index=ListBox.SelectedIndex;
if (index == lst.Count - 1)
ListBox.SelectedIndex = 0;
else
this.ListBox.SelectedIndex = index + 1;
Cna您共享代码,修改集合如果要将其放回同一索引中,为什么必须将其删除?
var index=ListBox.SelectedIndex;
if (index == lst.Count - 1)
ListBox.SelectedIndex = 0;
else
this.ListBox.SelectedIndex = index + 1;