Remove from ListBox

  • Thread starter Thread starter Guest
  • Start date Start date
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.
 
Morten Wennevik said:
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.
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??
 
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.
 
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);
 
Back
Top