A.sp.net clear ListBox list items (delete all items)

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.