{"record":{"id":"00db62d65b0cb6c9","repo":"dotnet/wpf","slug":"sr-cannotfindremoveditem","errorCode":null,"errorMessage":"SR.CannotFindRemovedItem","messagePattern":"SR\\.CannotFindRemovedItem","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"critical","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/ItemContainerGenerator.cs","lineNumber":2250,"sourceCode":"                    if (itemIsInCurrentBlock)\n                    {\n                        // we don't know where it is in this block, so assume\n                        // it's the very first item.\n                        offsetFromBlockStart = 0;\n                        position = new GeneratorPosition(containerIndex-1, 1);\n                        break;\n                    }\n                }\n\n                correctIndex += block.ItemCount;\n                containerIndex += block.ContainerCount;\n            }\n\n            if (block == _itemMap)\n            {\n                // There's no way of knowing which unrealized block it belonged to, so\n                // the data structure can't be updated correctly.  Sound the alarm.\n                throw new InvalidOperationException(SR.CannotFindRemovedItem);\n            }\n        }\n\n\n        // establish the link from the container to the corresponding item\n        internal static void LinkContainerToItem(DependencyObject container, object item)\n        {\n            // always set the ItemForItemContainer property\n            container.ClearValue(ItemForItemContainerProperty);\n            container.SetValue(ItemForItemContainerProperty, item);\n\n            // for non-direct items, set the DataContext property\n            if (container != item)\n            {\n                #if DEBUG\n                // Some ancient code at this point handled the case when DataContext\n                // was set via an Expression (presumably a binding).  I don't think\n                // this actually happens any more.  Just in case...","sourceCodeStart":2232,"sourceCodeEnd":2268,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/ItemContainerGenerator.cs#L2232-L2268","documentation":"During OnItemRemoved, the generator locates the block holding the removed item in its item map. If the item is not found in any realized block (the search reaches the sentinel _itemMap), the generator cannot know which unrealized block to update and throws InvalidOperationException SR.CannotFindRemovedItem, since silently skipping would corrupt the map.","triggerScenarios":"A CollectionChanged Remove/Reset event reports an item the generator has no record of — e.g. the collection was modified without notifications, events were missed, or a custom collection raises Remove for an item it never raised Add for.","commonSituations":"Custom INotifyCollectionChanged sources with out-of-sync events; dropping/pausing events (e.g. during bulk edits) then raising a partial Remove; loading collections from another thread.","solutions":["Make the source collection's notifications complete and ordered: every removed item must have been previously reported.","Raise Reset instead of Remove when the collection state diverged from notification history.","Rebind ItemsSource (or refresh) if notifications were lost, so the generator rebuilds its map."],"exampleFix":"// before\ncollection.Remove(x); // x was never announced via Add -> generator throws\n\n// after\nif (collection.Contains(x))\n    collection.Remove(x);\nelse\n    collectionOnReset(); // or raise Reset to resync the generator","handlingStrategy":"try-catch","validationCode":"if (!collection.Contains(item) && pendingRemovals.Contains(item))\n    raiseResetInsteadOfRemove(); // resync generator","typeGuard":null,"tryCatchPattern":"try { /* update binding */ }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"removed item\"))\n{\n    itemsControl.Items.Refresh(); // rebuild generator map\n}","preventionTips":["Ensure every Remove notification corresponds to a previously announced Add.","Raise Reset when notification history may have diverged.","Avoid dropping/batching CollectionChanged events."],"tags":["wpf","itemcontainergenerator","collection-changed","invariant"],"backgroundTag":"internal-invariant-violation","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}