C# removing the current item in a listbox

让人想犯罪 __ 提交于 2019-12-12 04:14:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!