在 C# 中为 ListBox 分配数据源时,如何从 ListBox 中删除所选项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/709562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 14:19:00  来源:igfitidea点击:

How to remove selected items from ListBox when a DataSource is assigned to it in C#?

c#

提问by Dhana

How to remove selected items from ListBox when a datasource is assigned to it in C#?

如何在 C# 中将数据源分配给 ListBox 时从 ListBox 中删除所选项目?

When trying to remove, got error

尝试删除时,出现错误

"Items collection cannot be modified when the DataSource property is set."

“设置 DataSource 属性后,无法修改项目集合。”



But when i try to remove item from datasource (datatable) ,

但是当我尝试从数据源(数据表)中删除项目时,

it thorws error as "datarow is not in current row collection".

它引发错误,因为“数据行不在当前行集合中”。

采纳答案by Chris Doggett

Find that item in the DataSource object and remove it, then re-bind the ListBox.

在 DataSource 对象中找到该项目并将其删除,然后重新绑定 ListBox。

EDIT:

编辑

Here's how you delete from a DataTable as your DataSource, regardless of the .NET version.

以下是从作为数据源的 DataTable 中删除的方法,无论 .NET 版本如何。

DataRowView rowView = listBox.SelectedItem as DataRowView;

if (null == rowView)
{
    return;
}

dt.Rows.Remove(rowView.Row);

I haven't tried with anything other than WinForms DataGridViews, but I highly recommend BindingListView, which is both faster than DataTables/Views and allows you to bind generic List<T>s as your DataSource.

我没有尝试过 WinForms DataGridViews 以外的任何东西,但我强烈推荐BindingListView,它比 DataTables/Views 更快,并且允许您将通用 List<T>s 绑定为您的数据源。

回答by nba bogdan

If the ListBox has a datasource assigned, you must remove items from the datasource and then rebind the ListBox

如果 ListBox 分配了数据源,则必须从数据源中删除项目,然后重新绑定 ListBox

回答by Justin Niessner

You need to modify the data source rather than the Items collection of the control. Depending on what kind of data source you are binding to, there are going to be different things you have to do so that your UI updates.

您需要修改数据源而不是控件的 Items 集合。根据您绑定到的数据源类型,您必须执行不同的操作才能更新 UI。

The best way is find a collection that fits your needs and implements IBindingList or IBindingListView. Those two interfaces implement even handlers that listen for a CollectionChanged event and update your UI accordingly.

最好的方法是找到一个适合您的需要并实现 IBindingList 或 IBindingListView 的集合。这两个接口甚至实现了侦听 CollectionChanged 事件并相应地更新您的 UI 的处理程序。

If your collection doesn't support those interfaces, you're going to have to re-bind your data source every time somebody adds/removes an item.

如果您的集合不支持这些接口,则每次有人添加/删除项目时,您都必须重新绑定数据源。

回答by Zack

Alternatively, use a list that implements IBindingList or inherits from BindingList. When objects are added or removed from a Binding List, any controls bound to it are automatically notified of the change and will update themselves accordingly. If you are using BindingList and your class also implements INotifyProperty changed, Any changes to class properties will also be updated automatically in the databinding control. For example, if a column in a datagrid(view) is bound to a property, "Name", and you change "Name" in the datasource, the datagrid will automatically update. If you add a new item to the datasource, the datagrid will update automatically. Binding List also supports notification in the other direction. If a user edits the "Name" field ina datagrid, the bound object will be updated automatically. Going off topic slightly, if you go a little further and impliment "SupportsSortingCore" and the associated methods in BindingList, you can add automatic sorting to your data. Clicking on a columnm header will automatically sort the list and display the header sort direction arrow.

或者,使用实现 IBindingList 或从 BindingList 继承的列表。在绑定列表中添加或删除对象时,绑定到它的任何控件都会自动收到更改通知,并将相应地更新自己。如果您正在使用 BindingList 并且您的类也实现了 INotifyProperty 更改,则对类属性的任何更改也将在数据绑定控件中自动更新。例如,如果数据网格(视图)中的列绑定到属性“名称”,并且您更改数据源中的“名称”,则数据网格将自动更新。如果向数据源添加新项目,数据网格将自动更新。绑定列表还支持另一个方向的通知。如果用户编辑数据网格中的“名称”字段,绑定的对象将自动更新。稍微偏离主题,如果您更进一步并在 BindingList 中实现“SupportsSortingCore”和相关方法,您可以为您的数据添加自动排序。单击列标题将自动对列表进行排序并显示标题排序方向箭头。

回答by Zack

its vary simple , assign a new blank value to listbox eg..

它的变化很简单,为列表框分配一个新的空白值,例如..

Dim ABC As New List(Of String)()

Dim ABC As New List(Of String)()

ListBox1.DataSource = ABC

ListBox1.DataSource = ABC

回答by Pinjata

ListBox implementation is bugged, you need to create a new data source instance for the component for it to recognize a change.

ListBox 实现有问题,您需要为组件创建一个新的数据源实例,以便它识别更改。

Eg:

例如:

ActivitiesList.DataSource = _activities;

_activities = new List<Activity>(_activities);
_activities.Remove((Activity)ActivitiesList.SelectedItem);

ActivitiesList.DataSource = _activities;

回答by g.g

when you get the message "Items collection cannot be modified when the DataSource property is set." setting the datasource to something else, empty list or null does not help when the code initializecomponent is not completed.

当您收到消息“设置 DataSource 属性时无法修改项目集合”。当代码 initializecomponent 未完成时,将数据源设置为其他内容、空列表或 null 无济于事。

to avoid that error, one must do the change of datasource or the item list during or after form load.

为避免该错误,必须在表单加载期间或之后更改数据源或项目列表。

I know it does not seem to make sense. Hoever, the visual studio designer will generate code in the form designer.cs or vb that will add items to the listbox if any code that changes the items is found before end of initialize components

我知道这似乎没有意义。但是,如果在初始化组件结束之前找到任何更改项目的代码,visual studio 设计器将在表单 Designer.cs 或 vb 中生成代码,这些代码会将项目添加到列表框

回答by Chris

While Chris Doggett posted a valid solution, I ran into problems while using it. By using that method it was not allowing a subsequent GetChanges(DataRowState.Deleted) to work properly.

虽然 Chris Doggett 发布了一个有效的解决方案,但我在使用它时遇到了问题。通过使用该方法,它不允许后续的 GetChanges(DataRowState.Deleted) 正常工作。

To better solve my problem, I only had to change a single line - the last line.

为了更好地解决我的问题,我只需要更改一行——最后一行。

DataRowView rowView = listBox.SelectedItem as DataRowView;

if (null == rowView)
{
    return;
}

rowView.Row.Delete();

This allowed my GetChanges call to work properly.

这允许我的 GetChanges 调用正常工作。

回答by Sali Hoo

This worked for me

这对我有用

        DataTable temp = (DataTable)lstBlocks.DataSource;
        temp.Rows.RemoveAt(position);