清除ListBox的列表項(刪除所有項目)


如何清除ListBox的列表項(刪除所有項目), 今天開發程序時,有嘗試使用此功能。一開始並不是很順利。循環所有item去做remove時,需要執行兩次才可以完成清除。debug進行步進跟蹤,發現在Listbox.Items.Count 每移除一個,Count隨之減少,而Capacity並沒有作相應變化。

在網上搜索相關資料,相當多用戶有相同要求,一次移除ListBox的列表所有項。方法均是用:

View Code
for ( int i =  0; i < Listbox1.Items.Count; i++)
        {
            Listbox1.Items.RemoveAt(i);
        }

 

或者:

View Code
foreach (ListItem li  in ListBox1.Items)
        { 
            ListBox1.Items.Remove(li);
        }

而后者會出現異常: Collection was modified; enumeration operation may not execute.

 

不管怎樣,下面是Insus.NET的解決方法,寫一個迭代器:

View Code
private  void IterationRemoveItem(ListBox listbox)
    {
         for ( int i =  0; i < listbox.Items.Count; i++)
        {
             this.ListBoxCondition.Items.RemoveAt(i);
        }

         for ( int j =  0; j < listbox.Items.Count; j++)
        {
            IterationRemoveItem(listbox);
        }
    }

 

在清除銨鈕事件中寫:

View Code
  protected  void ButtonClear_Click( object sender, EventArgs e)
    {  
       IterationRemoveItem( this.ListBox1);       
    }


可以從下面看到操作效果:


免責聲明!

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



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