简体   繁体   English

ListBox.Items和ListBox.SelectedItems是否已链接?

[英]Are ListBox.Items and ListBox.SelectedItems linked?

I'm working on a WinForms project, on which there is a TextBox where the user can input a search query, and a ListBox where all items are visible and matched items highlighted. 我正在开发一个WinForms项目,其中有一个用户可以输入搜索查询的TextBox ,以及一个ListBox ,其中所有项目都是可见的,并且匹配的项目突出显示。

When I'm iterating through ListBox.Items and modifying ListBox.SelectedItems , I get an InvalidOperationException: List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change. 当我迭代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. InvalidOperationException: List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

Here's the code 这是代码

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
    }
}

I've already thought of a better solution, but I would still like to know why the exception happened. 我已经想过一个更好的解决方案,但我仍然想知道为什么会发生异常。

Is there some kind of link between ListBox.Items and ListBox.SelectedItems , or why does modifying one, make enumerating through the other impossible? ListBox.ItemsListBox.SelectedItems之间是否有某种联系,或者为什么修改一个,通过另一个不可能进行枚举?

Per MSDN ListBox.Items , 每个MSDN ListBox.Items you would want to add items through the following code: 您可能希望通过以下代码添加项目:

listbox.Items.Add(); listbox.Items.Add();

EDIT: (I meant to add the following after rereading the ? but my laptop turned off due to low battery) 编辑:(我的意思是重新阅读之后添加以下内容?但我的笔记本电脑因电池电量不足而关闭)

   listBox1.SetSelected(<index>, true);
   listBox1.SetSelected(<index>, true);
   listBox1.SetSelected(<index>, true);

Items are not just the objects in the ListBox but also its state like the selected state. 项目不仅仅是ListBox中的对象,还有所选状态的状态。 So you need to use a loop without an Enumerator to change the state of an item regardless of the way you change the state. 因此,无论您更改状态的方式如何,都需要使用不带Enumerator的循环来更改项的状态。 Makes no difference if you use SelectedItems, SelectedIndices, SetSelected or whatever. 如果您使用SelectedItems,SelectedIndices,SetSelected或其他什么,则没有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM