我正在开发一个 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
,或者为什么修改一个,就不可能通过另一个进行枚举?
最佳答案
根据 MSDN ListBox.Items ,
您希望通过以下代码添加项目:
listbox.Items.Add();
编辑:(我打算在重读后添加以下内容?但我的笔记本电脑因电池电量不足而关闭)
listBox1.SetSelected(<index>, true);
listBox1.SetSelected(<index>, true);
listBox1.SetSelected(<index>, true);
关于c# - ListBox.Items 和 ListBox.SelectedItems 是否链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15220025/