Posts By Category

Posts By Date

Resources:

C# Books
ASP.NET Books DotNet4All








If you like to support this site, feel free to make a donation to support improvements.

Thank you!

Monetize Your Blog

Removing Items From a List Control (Visual C#)

I was writing a Windows Application and I had a very simple need: Remove all Selected items from a ListBox control. If you have tried to simple use code like the one below:

foreach ( int selectedIndex in myListBox.SelectedIndices)

{

    myListBox.Items.RemoveAt(selectedIndex);

}

 

You know it wouldn't work, because as soon as you remve the first selected index, your ListBox.Items array has changed indecies as a result of the first removal. So I Googled arround for some quick code to copy, and was surprised after opening the first 6-7 search results that none had the answer to my need, so I wrote my own code... here it is:

 

while (myListBox.SelectedItems.Count > 0)

{

    myListBox.Items.Remove(myListBox.SelectedItems[0]);

}

 

This should take care of the problem.

kick it on DotNetKicks.com

Feedback

Posted on 1/9/2012 12:00:56 PM

while (myListBox.SelectedItems.Count > 0)
{
myListBox.Items.Remove(myListBox.SelectedItems[0]);
}

When you select last item in the list box, all the items will be removed with this code.

Posted on 11/22/2011 5:31:34 AM

hello i need to know how to remove selected items or values in combobox in .net using c sharp codings

Posted on 8/28/2011 11:28:01 AM

All good, but my program tells me "Items collection cannot be modified when the DataSource property is set."

How do I fix this?
Help will be much appreciated

Posted on 4/11/2011 4:24:44 PM

Thank You Very much

Posted on 1/7/2011 5:37:48 AM

Great approche really cool and very use full code snippet thanks for sharing book marked.. :)

Posted on 4/24/2010 12:52:48 AM

THANK YOU!!! I searched and searched and was not able to find a good solution to remove multiple selected items. A lot of other websites gave crap solutions. Yours work perfectly! Thank you!

Posted on 9/16/2008 11:59:04 AM

And the ASP.NET version:
while (ListBox1.GetSelectedIndices().Length > 0)
ListBox1.Items.Remove(ListBox1.SelectedItem);

Posted on 9/11/2008 2:54:29 AM

Here is the code for your solution.

ListBox.SelectedObjectCollection Obj = new ListBox.SelectedObjectCollection(listBox1);
for (int i = Obj.Count - 1; i >= 0; i--)
{
listBox1.Items.Remove(Obj[i]);
}

1). In ListBox.SelectedObjectCollection Pass the Listbox

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 


Copyright © 2007 Yousef Mannaa. All material on this site is copyrighted.
Do not publish or reproduce any of this material without written permission from the Author