简体   繁体   中英

Unhandled exception argumentnullexception in mscorlib.dll when updating a DataGrid

So I have a wpf application that has a datagrid to display items from a database. I want to refresh the items so I have implemented a refresh method to replace items that needs to be refreshed.

The Datagrid itemssource is bound to a ICollectionView that has an observablecollection with the items as source.

It looks like this:

private async Task RefreshContentOrders()
{   
    _isRefreshingContentOrders = true;
    var orders = await _contentOrderSession.GetAllContentOrdersAvaliableToUser(CurrentUser);
    foreach (var order in orders)
    {
        var currentItem = Orders.FirstOrDefault(x =>x!=null&& x.Id == order.Id);
        if (currentItem == null)
            Orders.Add(currentItem);
        else
        {
        Orders.Remove(currentItem);
        Orders.Add(order);                 
        }
    }    
    _isRefreshingContentOrders = false;
}

I can refresh my list without a problem as long as there are no new items. If I add a new item to my list and refresh using this method my application throws an exception in mscorlib.dll when I scroll down to look at the new item. The following message and stacktrace are shown:

Message: {"Value can not be null.\\r\\nParametername: key"}

Stacktrace:

   vid System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   vid System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   vid System.Windows.Controls.DataGridItemAttachedStorage.TryGetValue(Object item, DependencyProperty property, Object& value)
   vid System.Windows.Controls.DataGridRow.RestoreAttachedItemValue(DependencyObject objectWithProperty, DependencyProperty property)
   vid System.Windows.Controls.DataGridRow.SyncProperties(Boolean forcePrepareCells)
   vid System.Windows.Controls.DataGridRow.PrepareRow(Object item, DataGrid owningDataGrid)
   vid System.Windows.Controls.DataGrid.PrepareContainerForItemOverride(DependencyObject element, Object item)
   vid System.Windows.Controls.ItemsControl.MS.Internal.Controls.IGeneratorHost.PrepareItemContainer(DependencyObject container, Object item)
   vid System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.PrepareItemContainer(DependencyObject container)
   vid System.Windows.Controls.VirtualizingStackPanel.InsertContainer(Int32 childIndex, UIElement container, Boolean isRecycled)
   vid System.Windows.Controls.VirtualizingStackPanel.AddContainerFromGenerator(Int32 childIndex, UIElement child, Boolean newlyRealized, Boolean isBeforeViewport)
   vid System.Windows.Controls.VirtualizingStackPanel.MeasureChild(IItemContainerGenerator& generator, IContainItemStorage& itemStorageProvider, IContainItemStorage& parentItemStorageProvider, Object& parentItem, Boolean& hasUniformOrAverageContainerSizeBeenSet, Double& computedUniformOrAverageContainerSize, Double& computedUniformOrAverageContainerPixelSize, Boolean& computedAreContainersUniformlySized, IList& items, Object& item, IList& children, Int32& childIndex, Boolean& visualOrderChanged, Boolean& isHorizontal, Size& childConstraint, Rect& viewport, VirtualizationCacheLength& cacheSize, VirtualizationCacheLengthUnit& cacheUnit, Boolean& foundFirstItemInViewport, Double& firstItemInViewportOffset, Size& stackPixelSize, Size& stackPixelSizeInViewport, Size& stackPixelSizeInCacheBeforeViewport, Size& stackPixelSizeInCacheAfterViewport, Size& stackLogicalSize, Size& stackLogicalSizeInViewport, Size& stackLogicalSizeInCacheBeforeViewport, Size& stackLogicalSizeInCacheAfterViewport, Boolean& mustDisableVirtualization, Boolean isBeforeFirstItem, Boolean isAfterFirstItem, Boolean isAfterLastItem, Boolean skipActualMeasure, Boolean skipGeneration, Boolean& hasBringIntoViewContainerBeenMeasured, Boolean& hasVirtualizingChildren)
   vid System.Windows.Controls.VirtualizingStackPanel.MeasureOverrideImpl(Size constraint, Nullable`1& lastPageSafeOffset, List`1& previouslyMeasuredOffsets, Nullable`1& lastPagePixelSize, Boolean remeasure)
   vid System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint)
   vid System.Windows.Controls.Primitives.DataGridRowsPresenter.MeasureOverride(Size constraint)
   vid System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   vid System.Windows.UIElement.Measure(Size availableSize)
   vid System.Windows.ContextLayoutManager.UpdateLayout()
   vid System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
   vid System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
   vid System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   vid System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   vid System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   vid System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   vid System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   vid System.Windows.Threading.DispatcherOperation.InvokeImpl()
   vid System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   vid System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   vid System.Windows.Threading.DispatcherOperation.Invoke()
   vid System.Windows.Threading.Dispatcher.ProcessQueue()
   vid System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   vid MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   vid MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   vid System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   vid System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   vid System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   vid MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   vid MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   vid System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   vid System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   vid System.Windows.Application.RunDispatcher(Object ignore)
   vid System.Windows.Application.RunInternal(Window window)
   vid System.Windows.Application.Run(Window window)
   vid System.Windows.Application.Run()
   vid White.Db.ContentOrderDb.App.Main() i C:\Revit Dev\GENERELLA\DATABASER\ContentOrderDb\White.Db.ContentOrderDb.Application\obj\Debug\App.g.cs:rad 0
   vid System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   vid System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   vid Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   vid System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   vid System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   vid System.Threading.ThreadHelper.ThreadStart()

If I instead recreate the ObservableCollection and ICollectionView everything works.

When I restart the application the new item that I added is there and everything seems normal.

I've been trying to figure out whats wrong for almost a day now, but I just cant seem to figure it out. Im running .Net 4.6.1 in visual studio 2015.

Its obvious that it has to do with the datagrid from the stacktrace, but Im having a really hard time pinning down what its not liking about my code.

Any thoughts?

看起来您在这里有一个错误:if(currentItem == null)Orders.Add(currentItem);

Without seeing more of the code I can't be sure but I assume Orders is your ObservableCollection? If so I think you might be trying to update it from a different thread than the UI thread.

What you can try to see is adding this in your constructor or where ever you are making your ObservableCollection.

BindingOperations.EnableCollectionSynchronization(Orders, Orders);

It will let you modify the collection from a different thread than the UI thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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