This is a migrated thread and some comments may be shown as answers.

Occasional NullReferenceException when ItemsSource is refreshed

8 Answers 107 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Jeremie
Top achievements
Rank 1
Jeremie asked on 04 Aug 2011, 09:02 PM
Hello,  I have a WPF application that utilizes the MVVM pattern.  On my view is a RadGridView defined as

<telerik:RadGridView Name="grdOrders" Grid.Row="1"
                                 AutoGenerateColumns="False"
                                 ItemsSource="{Binding LineItems}"
                                 SelectedItem="{Binding Path=SelectedLineItem}"
                                 IsSynchronizedWithCurrentItem="True"
                                 IsReadOnly="True"
                                 ClipboardCopyMode="Cells"
                                 RowStyleSelector="{StaticResource backorderStyleSelector}"
                                 ScrollViewer.HorizontalScrollBarVisibility="Auto"
                                 ScrollViewer.VerticalScrollBarVisibility="Auto" MouseDoubleClick="grdOrders_MouseDoubleClick" SelectionMode="Extended">
                                 <i:Interaction.Behaviors>
                    <b:MultiSelectBehavior SelectedItems="{Binding Path=SelectedLineItems}" />
                </i:Interaction.Behaviors>
                    <telerik:RadGridView.Columns>
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=GPPONumber}" Header="GP PO Number" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=LineItemId}" Header="Line Item Id" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=Quantity}" Header="Quantity" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=PartNumber}" Header="Part Number" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=Description}" Header="Description" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=WarehouseCode}" Header="Warehouse" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=WarehouseBin}" Header="Bin Location" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=ShippingMethod}" Header="Shipping Method" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=VendorName}" Header="Vendor Name" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=Salesrep}" Header="Sales Rep" />
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=SourcedBy}" Header="Sourced By" />
                    <telerik:GridViewDataColumn DataMemberBinding="{Binding Path=Backordered}" Header="B/O?" />
                </telerik:RadGridView.Columns>
                </telerik:RadGridView>

Corresponding in my ViewModel I have a property

public ObservableCollection<WarehouseLineItemProxy> LineItems
    {
      get
      {
        return lineItems;
      }
      set
      {
        lineItems = value;
        RaisePropertyChanged(() => LineItems);
        ViewOrderInfoCommand.RaiseCanExecuteChanged();
      }
    }

On the View Model is a timer that refreshes the data every 60 seconds

refreshTimer = new DispatcherTimer();
refreshTimer.Interval = TimeSpan.FromSeconds(60);
refreshTimer.Tick += new EventHandler(refreshTimer_Tick);

The tick event and refresh method

/// <summary>
    /// Handles the Tick event of the refreshTimer control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void refreshTimer_Tick(object sender, EventArgs e)
    {
      refreshTimer.Stop();
      RefreshLineItems(new object());
      refreshTimer.Start();
    }
 
/// <summary>
    /// Refreshes the line items.
    /// </summary>
    /// <param name="arg">The arg.</param>
    private void RefreshLineItems(object arg)
    {
      if (!worker.IsBusy)
      {
        ShowBusyIndicator = true;
        worker.RunWorkerAsync();
        refreshTimer.Stop();
        refreshTimer.Start();
      }
    }

worker is a BackgroundWorker that allows me to load data asynchronously

/// <summary>
    /// Handles the DoWork event of the worker control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
      e.Result = adapter.LoadWarehouseOrders();
    }
 
/// <summary>
    /// Handles the RunWorkerCompleted event of the worker control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      Dispatcher.CurrentDispatcher.BeginInvoke(new Action<ObservableCollection<WarehouseLineItemProxy>>(this.UpdateGridData), e.Result);
    }   
 
/// <summary>
    /// Updates the grid data.
    /// </summary>
    /// <param name="lineItems">The line items.</param>
    private void UpdateGridData(ObservableCollection<WarehouseLineItemProxy> lineItems)
    {
      LineItems = lineItems;
      ShowBusyIndicator = false;
    }

Occasionally in Production users will get a NullReferenceException at some point when the grid is trying to re-draw.  Here is the stack trace.

at Telerik.Windows.Controls.GridView.Automation.GridViewCellAutomationPeer.GetNameCore() in c:\Builds\WPF_Scrum\Release_WPF\Sources\Development\Controls\GridView\GridView\GridView\Automation\GridViewCellAutomationPeer.cs:line 146
   at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
   at System.Windows.Automation.Peers.AutomationPeer.UpdatePeer(Object arg)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at PartsFinder.Chimera.App.Main() in d:\TeamCityWork\PARTSFinderSlnProd\Chimera\PartsFinder.Chimera\obj\x86\Prod-Warehouse\App.g.cs:line 50

This exception doesn't happen every time, in fact it is very random.  But the users get annoyed when it happens several times during the day.  Does anyone have any ideas?

Thanks

8 Answers, 1 is accepted

Sort by
0
Yordanka
Telerik team
answered on 05 Aug 2011, 07:47 AM
Hi Jeremie,

The exception should not appear with the latest official version - Q2 2011.
 
Best wishes,
Yordanka
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get now >>

0
Rayne
Top achievements
Rank 1
answered on 31 Aug 2011, 10:15 PM
I'm having the same problem with the grid. And yes, I'm using a background worker to set the property that is bound to ItemsSource.

I'm also having this problem on a grid that is already bound. When the user tries to create a new row, the new row has one column that is a comboBox column. When they drop down the list, then select an item in the combobox, they get this error and it then shuts down the application. There is no backgroundworker at play on this view/viewmodel.

I'm using Q2 2011 controls (2011.2.712.40). It is very random, but when it starts happening, it happens consistently. I cannot reproduce this error on my development machine. Could it have to do with performance of their machine?
0
Ivan Ivanov
Telerik team
answered on 03 Sep 2011, 03:30 PM
Hi Rayne,

 I have tested several scenarios manipulating the data through a BackgroundWorker, without having any success in reproducing this issue. I am attaching my test project for your reference. Would you please confirm whether the issue is reproducible on your side? However, sometimes the automation problems prove to be system specific, so that some info on your system environment or a demo project  would be highly appreciated.

Greetings,

Ivan Ivanov
the Telerik team

 

Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

0
Rayne
Top achievements
Rank 1
answered on 06 Sep 2011, 01:29 PM
I'm not sure I could create a demo project, because since it's not happening on my machine, I can't even reproduce it myself. It's just a select few machines that have the problem.

It does seem to go away if the user uninstalls and re-installs the application. But so far I've seen this happen on both WinXP and Win7. And it's occurring most frequently on a component that isn't using a background worker.
0
Rayne
Top achievements
Rank 1
answered on 06 Sep 2011, 05:17 PM
I've had another user complain about this issue, but this time it is triggered when they select the tab with the problem grid.
I'm wondering if I've overloaded the tab and/or grid.

The topmost tabItem contains a child tab control. This control is bound to a collection of items and I've defined an item template and a content Template. I've also defined a Item container style to not display (Visibility is collapsed) items in the collection where IsDeleted = false. The Content template is defined as another user control. I originally had it defined in parent user control, but then moved it to its own user control because I needed access to the contained grid so I could add a context menu to one of the grid columns and set its data context. The Data Template User Control contains a grid with several columns for which I've defined the cell edit templates.

I've read somewhere online that these random null reference exceptions with automation can occur if you change the control template and forget a part of the original template. But I'm not changing any control templates. I've only been defining data templates.

And as I said previously. It doesn't occur on every machine, just some of my users randomly on WinXP and Win7.  And the error seems to persistently be tied to the components of the tabItem mentioned above. When it works well, it works beautifully. When it doesn't, it just crashes my application.
0
Ivan Ivanov
Telerik team
answered on 07 Sep 2011, 07:01 AM
Hi Rayne,

Conditionally changing GridViewRows' Visibility to Collapsed is not the recommended approach to achieve this goal. I presume that this might be the source of the issue. Would you please try temporary excluding this logic from your code and confirm whether the problem still persists?

Regards,
Ivan Ivanov
the Telerik team

Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

0
Rayne
Top achievements
Rank 1
answered on 07 Sep 2011, 01:31 PM
I'm setting the Collapsed property on the ItemsContainer for the TabControl, not the GridView. The Tab Control is bound to a collection of items. Each tab Item then uses a gridview to show a child collection of the items bound to the TabControl. Makes sense?

So I have for example, a collection of Persons. Each person is represented by a Tab Item. Each person has a collection of addresses that is displayed on a gridview on the tab.  If the person is Marked IsDeleted, then I'm setting the Visibility of the Tab to Collapsed.

On the GridView (for the child collection of addresses) I'm using a filter Descriptor filter out items marked IsDeleted.

And on another note...I have found that one of my users that is having this problem consistently is on a new Tablet PC.
0
Ivan Ivanov
Telerik team
answered on 12 Sep 2011, 01:57 PM
Hi Rayne,

We have applied a fix that targets this issue. It will be available with our next internal build. We will appreciate your feedback on this topic after you have tested your code with the new version.

All the best,
Ivan Ivanov
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Tags
GridView
Asked by
Jeremie
Top achievements
Rank 1
Answers by
Yordanka
Telerik team
Rayne
Top achievements
Rank 1
Ivan Ivanov
Telerik team
Share this question
or