[英]Removing an item from listbox in winform
I am using VS2010, C#, .Net 4.0 and WinFormApplication. 我正在使用VS2010,C#、. Net 4.0和WinFormApplication。
I have a listbox which is populated from a datasource. 我有一个从数据源填充的列表框。 I want to remove an item at a time when they are double clicked. 我想在双击它们时一次删除它们。
I read somewhere that if I populate my listbox from a datasource, no item can be removed. 我在某处读到,如果我从数据源填充列表框,则无法删除任何项目。 Is this true? 这是真的? If not, then how can I remove individual items? 如果没有,那么我该如何删除单个物品?
I tried the following: 我尝试了以下方法:
listbox1.Items.Remove(listbox1.SelectedIndex);
listbox1.Items.Remove(listbox1.SelectedIndex);
lbTableColumns.Items.Remove(lbTableColumns.SelectedItem);
which cause the following error: 导致以下错误:
ERROR: Items collection cannot be modified when the DataSource property is set. 错误:设置了DataSource属性后,无法修改项目集合。
When using a DataBinding
you cannot remove items from the ListBox
, just as the error states. 使用DataBinding
,不能像错误状态一样从ListBox
删除项目。 What would happen if the object changes within the DataSource
, but has been removed from the presentation? 如果对象在DataSource
更改但已从演示文稿中删除,将会发生什么情况?
If you are working with DataSources you need to remove the object from the DataSource itself. 如果您正在使用数据源,则需要从数据源本身中删除对象。 Try something like this: 尝试这样的事情:
IList<MyObj> myList = new List<MyObj>();
private void DataBind()
{
myListBox.BeginUpdate();
myListBox.DataSource = myList;
myListBox.EndUpdate();
}
private void OnMyListBoxItemDoubleClicked(object sender, EventArgs e)
{
myList.RemoveAt(myListBox.SelectedIndex);
DataBind();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.