从 ObservableCollection 类中删除记录
我正在开发 WPF 应用程序,并且收到错误,这意味着我无法从 ObservableCollectionClass 中删除项目。我的代码如下所示。
它正在工作,但记录未删除。
SampleDB conn = new SampleDB(Helper.GetPath());
var Query = from a in conn.UserInfo
where a.ID == (int)iSelectedID
select new UserDatail { ID = a.ID, Name = a.Name, Address = a.Address, City = a.City, Pin = a.Pin, Phone = a.Phone };
foreach (var item in Query)
{
userDetail.Remove(item);
}
dgPorfomance.ItemsSource = userDetail;
dgPorfomance.Items.Refresh();
I am Working on WPF Application and I am getting error means I am not able to Remove Item from the ObservableCollectionClass My Code is given bellow..
it's working but the record is not delete.
SampleDB conn = new SampleDB(Helper.GetPath());
var Query = from a in conn.UserInfo
where a.ID == (int)iSelectedID
select new UserDatail { ID = a.ID, Name = a.Name, Address = a.Address, City = a.City, Pin = a.Pin, Phone = a.Phone };
foreach (var item in Query)
{
userDetail.Remove(item);
}
dgPorfomance.ItemsSource = userDetail;
dgPorfomance.Items.Refresh();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ObservableCollection
找不到您要删除的对象,因为它与集合中当前的对象不同(您刚刚使用new
创建了该对象)。您需要重写
UserDetail
类中的Equals
,以便可以根据您的规则测试两个实例的相等性:请注意,当您重写
Equals
时,您还必须重写GetHashCode
:The
ObservableCollection
can't find the object you want to remove, because it's different from the one currently in the collection (you just created it withnew
).You need to override
Equals
in yourUserDetail
class so that two instances can be tested for equality based on your rules:Note that when you override
Equals
, you must also overrideGetHashCode
:您正试图从最初不包含该对象的集合中删除一个对象。
解释:
当您这样做时,
您必须确保循环中的每个项目与集合中包含的项目是同一实例。在这里,情况并非如此:这些项目可能看起来相同,但它们实际上是同一项目的 2 个不同实例,因为您首先从查询而不是从集合中获取这些项目,
所以您应该执行类似的操作在这种情况下:
you are trying to remove an object from a collection that does not contain this object in the first place.
explanation:
when you do
you have to be sure that each item in your loop is the same instance than the item contained in the collection. Here, this is not the case: the items may appear to be the same, but they are actually 2 different instances of the same item, as you first get those items from a query and not from your collection
so you should do something like this in this case:
我认为错误可能是“集合已修改;枚举操作可能无法执行”。
这就是使用 ienumerable 接口迭代集合的 foreach 语句的问题。为了克服这个问题,您可以制作当前集合 [.ToList() 方法] 的浅表副本并迭代每个集合。
解决办法是:
foreach(Query.ToList()中的var item)
{
userDetail.Remove(item);
}
I think the error might be 'Collection was modified; enumeration operation may not execute'.
This is the problem of foreach statement with ienumerable interface to iterate through a collection. To overcome this you can make a shallow copy of the present collection[.ToList() method] and iterate through each.
The solution is:
foreach (var item in Query.ToList())
{
userDetail.Remove(item);
}