此枚舉數綁定到的列表已被修改,僅在列表沒有更改時才能使用枚舉數


剛剛在刪除和設置ListBox中的選中項的時候遇到這種錯誤提示。
原因是遍歷ListBox中的Items的時候同時操作Item.
解決辦法就是改foreach()遍歷Items為for()遍歷Item[i]
///   <summary>
///  設置ListBox選中項
///   </summary>
///   <param name="listBox"></param>
///   <param name="selStr"></param>
private  void SelListBox(System.Windows.Forms.ListBox listBox,  string selStr)
{
     // foreach (object obj in listBox.Items)
    
// {
    
//     if (obj.ToString() == selStr)
    
//     {
    
//         listBox.SelectedItems.Add(obj);
    
//     }
    
// }
     for ( int i =  0; i < listBox.Items.Count; i++)
    {
         if (listBox.Items[i].ToString() == selStr)
        {
            listBox.SelectedItems.Add(listBox.Items[i]);
        }
    }
}
ListBox.ClearSelected   方法     [C#] 
調用此方法等效於將   SelectedIndex   屬性設置為負一   (-1)。
可以使用此方法快速取消選擇列表中的所有項。 

foreach(   object   d   in   listBox2.SelectedItems) 
這一行有問題,當刪除其中一個選項時,listBOx的所選項已經被更改了,再調用foreach,當然會有問題!
for ( int i=listBox1.Items.Count- 1; i>- 1; i--)
{
     if (listBox1.GetSelected(i))
    {
         listBox1.Items.RemoveAt(i);
    }
}
需要注意兩點。 
1。 GetSelected(i) 獲得選中的狀態
2。 循環遍歷需要用倒序, 不然刪除選項后, index會變化, 造成后刪除的序號錯誤。
url: http://greatverve.cnblogs.com/archive/2012/07/31/foreach-listbox.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM