c# - ListBox.Items 和 ListBox.SelectedItems 是否链接?

标签 c# winforms enumeration

我正在开发一个 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/

相关文章:

c# - 我的 Access 数据库不更新 (ASP.NET)

C# 动态 MenuStrip(不接触窗体)

c# - 我们如何在表单应用程序的标签中放置自定义日期格式?

C# - 自动添加 'X' 个按钮,一个接一个。

c# - 使 GetEnumerator 线程安全

C# 4 System.Threading.Tasks 性能询问

c# - ASP.NET MVC - GET 请求上的 CSRF

c# - 将所有标记的字符串更改为另一个字符串

Java从多次存在的config.properties文件中获取某个属性

powershell - Where-Object 过滤器意外匹配整个输入集合,Get-Member 显示集合类型而不是元素类型