470,636 Members | 1,582 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,636 developers. It's quick & easy.

Remove from ListBox

How can I remove some selected items from the listBox in the run time ??

Nov 16 '05 #1
4 18165
Hi mostafa atalla,

ListBox.SelectedObjectCollection s = listBox1.SelectedItems;

while(s.Count > 0)
listBox1.Items.Remove(s[0]);

The SelectedObjectCollection is directly tied to the listbox items and when you remove an item, the item is also gone from the collection.

--
Happy coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #2


"Morten Wennevik" wrote:
Hi mostafa atalla,

ListBox.SelectedObjectCollection s = listBox1.SelectedItems;

while(s.Count > 0)
listBox1.Items.Remove(s[0]);

The SelectedObjectCollection is directly tied to the listbox items and when you remove an item, the item is also gone from the collection.

--
Happy coding!
Morten Wennevik [C# MVP]

Dear sir :
when I wrote the previous code and run , the following exception appeared :
An unhandled exception of type 'System.ArgumentException' occurred in system.windows.forms.dll
Additional information: Cannot modify the Items collection when the DataSource property is set.

the DataSource property must be set to the database,what can i do to solve this problem??
Nov 16 '05 #3
When you use a datasource, you need to remove the items from the source. The ListBox will update itself when the source changes.

If you only have one selected item you can remove it like this

DataRowView drw = (DataRowView)listBox1.SelectedItem;
dataSet1.Tables[0].Rows.Remove(drw.Row);

However, I couldn't manage to get the previous while loop to work with the DataSet as it ended up removing all rows, selected or not, or it only removed the first row.

--
Happy coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #4
You need to save the selected rows before you start removing them.

ListBox.SelectedObjectCollection s = listBox1.SelectedItems;

ArrayList list = new ArrayList();

foreach(object o in s) // store the rows outside selectedobjectcollection
list.Add(o);

foreach(DataRowView drw in list)
dataSet1.Tables[0].Rows.Remove(drw.Row);

--
Happy coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Supra | last post: by
4 posts views Thread by Bilo | last post: by
3 posts views Thread by Hrcko | last post: by
1 post views Thread by deepak | last post: by
3 posts views Thread by Bill Nguyen | last post: by
11 posts views Thread by Andrus | last post: by
1 post views Thread by Korara | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.