By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,771 Members | 1,709 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,771 IT Pros & Developers. It's quick & easy.

Remove from ListBox

P: n/a
How can I remove some selected items from the listBox in the run time ??

Nov 16 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
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

P: n/a


"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

P: n/a
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

P: n/a
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.