我正在开发一个 WinForms 项目,TextBox用户可以在其中输入搜索查询,并且ListBox所有项目都可见并突出显示匹配的项目。
当我迭代ListBox.Items和修改ListBox.SelectedItems时,我得到一个InvalidOperationException: List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.
这是代码
private void SearchTextBox_TextChanged(object sender, EventArgs e)
{
listBox.ClearSelected();
foreach (var item in listBox.Items) // Exception happens here...
{
if (item.ToString().Contains(SearchTextBox.Text))
listBox.SelectedItems.Add(item); // ... but I'm not modifying listBox.Items
}
}
我已经想到了一个更好的解决方案,但我仍然想知道为什么会发生异常。
和 之间是否存在某种联系ListBox.Items,ListBox.SelectedItems或者为什么修改一个会使枚举另一个变得不可能?