Remove Record From ObservableCollection Class
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.Us开发者_Python百科erInfo
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();
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 with new
).
You need to override Equals
in your UserDetail
class so that two instances can be tested for equality based on your rules:
public override bool Equals(object o)
{
UserDetail other = o as UserDetail;
if (other != null)
{
return this.Id == other.Id;
}
return false;
}
Note that when you override Equals
, you must also override GetHashCode
:
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
you are trying to remove an object from a collection that does not contain this object in the first place.
explanation:
when you do
foreach (var item in Query)
{
userDetail.Remove(item);
}
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:
foreach (var item in Query)
{
foreach (var itemInCollection in userDetail)
{
if (itemInCollection.Id == item.Id)
userDetail.Remove(itemInCollection );
}
}
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);
}
精彩评论