[英]Are ListBox.Items and ListBox.SelectedItems linked?
我正在開發一個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.
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);
項目不僅僅是ListBox中的對象,還有所選狀態的狀態。 因此,無論您更改狀態的方式如何,都需要使用不帶Enumerator的循環來更改項的狀態。 如果您使用SelectedItems,SelectedIndices,SetSelected或其他什么,則沒有任何區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.