简体   繁体   English

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

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

How to remove selected items from ListBox when a datasource is assigned to it in C#?在 C# 中分配数据源时如何从 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".它将错误作为“数据行不在当前行集合中”。

Find that item in the DataSource object and remove it, then re-bind the ListBox.在 DataSource object 中找到该项并将其删除,然后重新绑定 ListBox。

EDIT :编辑

Here's how you delete from a DataTable as your DataSource, regardless of the .NET version.无论 .NET 版本如何,这是从 DataTable 中删除作为 DataSource 的方法。

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 绑定为数据源。

Alternatively, use a list that implements IBindingList or inherits from BindingList.或者,使用实现 IBindingList 或从 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.如果您正在使用 BindingList 并且您的 class 也实现了 INotifyProperty 更改,则对 class 属性的任何更改也将在数据绑定控件中自动更新。 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.如果用户在数据网格中编辑“名称”字段,绑定的 object 将自动更新。 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.稍微偏离主题,如果您进一步了解 go 并在 BindingList 中实现“SupportsSortingCore”和相关方法,则可以为您的数据添加自动排序。 Clicking on a columnm header will automatically sort the list and display the header sort direction arrow.单击列 m header 将自动对列表进行排序并显示 header 排序方向箭头。

when you get the message "Items collection cannot be modified when the DataSource property is set."当您收到消息“设置 DataSource 属性时无法修改项目集合”时。 setting the datasource to something else, empty list or null does not help when the code initializecomponent is not completed.当代码初始化组件未完成时,将数据源设置为其他内容、空列表或 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 形式生成代码,这些代码会将项目添加到列表框

This worked for me这对我有用

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

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;

If the ListBox has a datasource assigned, you must remove items from the datasource and then rebind the ListBox如果 ListBox 分配了数据源,则必须从数据源中删除项目,然后重新绑定 ListBox

You need to modify the data source rather than the Items collection of the control.您需要修改数据源而不是控件的 Items 集合。 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.根据您绑定到的数据源类型,您需要执行不同的操作才能更新 UI。

The best way is find a collection that fits your needs and implements IBindingList or IBindingListView.最好的方法是找到一个适合您需要并实现 IBindingList 或 IBindingListView 的集合。 Those two interfaces implement even handlers that listen for a CollectionChanged event and update your UI accordingly.这两个接口甚至实现了侦听 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.如果您的集合不支持这些接口,那么每次有人添加/删除项目时,您都必须重新绑定您的数据源。

While Chris Doggett posted a valid solution, I ran into problems while using it.虽然 Chris Doggett 发布了一个有效的解决方案,但我在使用它时遇到了问题。 By using that method it was not allowing a subsequent GetChanges(DataRowState.Deleted) to work properly.通过使用该方法,它不允许后续的 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 调用正常工作。

its vary simple, assign a new blank value to listbox eg..它的变化很简单,为列表框分配一个新的空白值,例如..

Dim ABC As New List(Of String)()将 ABC 调暗为新列表(字符串)()

ListBox1.DataSource = ABC ListBox1.DataSource = ABC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM