How to clear the list items of ListBox (delete all projects). I tried to use this function when developing a program today. It was not very smooth at the beginning. To remove all items in a loop, you need to perform the removal twice. Debug performs step-by-step tracking and finds that each time Listbox. Items. Count is removed, the Count is reduced, and the Capacity is not changed accordingly.
Search for related materials on the Internet. Many users have the same requirements. All items in The ListBox list are removed at a time. All methods are used:
Copy codeThe Code is as follows:
For (int I = 0; I <Listbox1.Items. Count; I ++)
{
Listbox1.Items. RemoveAt (I );
}
Or:
Copy codeThe Code is as follows:
Foreach (ListItem li in ListBox1.Items)
{
ListBox1.Items. Remove (li );
}
The latter will encounter an exception: Collection was modified; enumeration operation may not execute.
In any case, the following is the Insus. NET solution to write an iterator:
Copy codeThe Code is as follows:
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 );
}
}
In the delete button event, write:
Copy codeThe Code is as follows:
Protected void ButtonClear_Click (object sender, EventArgs e)
{
IterationRemoveItem (this. ListBox1 );
}
You can see the operation result below: