问题
I have a List which holds a bunch of objects, the contents of the list is then added to a listbox control. My question is, how can I remove the current item in the list which will in turn remove the current item in the listbox?
回答1:
you can just get the selected index in the selectedindex_changed event handler, remove the object at that index and repopulate the listbox
int index = listbox.SelectedIndex();
listThatHoldsObjects.RemoveAt(index);
listbox.ItemsSource = listThatHoldsObjects
回答2:
You can BindingList<object>
to bind it to the list and associate the list of object List<object>
with this BindingList
. Once you remove an item from BindingList
it will remove the same item from both List
and ListBox
List<object> list = new List<object>();
list.Add("test");
list.Add("test1");
BindingList<object> bindingList;
bindingList = new BindingList<object>(list);
listBox1.DataSource = bindingList;
bindingList.Remove("test");
回答3:
Consider using the BindingList<T>
class (found here) and bind it to the ListBox
.
If you do not want that, you can always use:
ListBox lb = new ListBox();
List<object> list = new List<object>();
list.RemoveAt(lb.SelectedIndex);
lb.Items.RemoveAt(lb.SelectedIndex);
来源:https://stackoverflow.com/questions/7377390/c-sharp-removing-the-current-item-in-a-listbox