I am using VS2010, C#, .Net 4.0 and 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.
When using a DataBinding
you cannot remove items from the ListBox
, just as the error states. What would happen if the object changes within the DataSource
, but has been removed from the presentation?
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.