I have a datagridview on my form.
the datagridview had the AutoResizeColumn set to Fill and everything worked fine.
I now changed it to All and when I click on the colum header a few time I get System.NullReferenceException.
I have one event that occurs when a row is clicked and I know the exception is not happening in there.
Below is a description of the error (sorry that it is so long). Any advice would be appreciated.
Is there anyway that I could just catch this error and prevent it from terminating my application?
System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.DataGridView.ComputeVisibleColumns() at System.Windows.Forms.DataGridView.LayoutScrollBars() at System.Windows.Forms.DataGridView.ComputeLayout() at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean useRowShortcut, Boolean computeVisibleRows, Boolean invalidInAdjustFillingColumns, Boolean repositionEditingControl) at System.Windows.Forms.DataGridView.OnColumnWidthChanged(DataGridViewColumnEventArgs e) at System.Windows.Forms.DataGridView.OnBandThicknessChanged(DataGridViewBand dataGridViewBand) at System.Windows.Forms.DataGridView.AutoResizeColumnInternal(Int32 columnIndex, DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal, Boolean fixedHeight) at System.Windows.Forms.DataGridView.AutoResizeAllVisibleColumnsInternal(DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFilter, Boolean fixedHeight) at System.Windows.Forms.DataGridView.OnAddedRow_PostNotification(Int32 rowIndex) at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged_PostNotification(CollectionChangeAction cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow dataGridViewRow, Boolean changeIsDeletion, Boolean changeIsInsertion, Boolean recreateNewRow, Point newCurrentCell) at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged(CollectionChangeEventArgs e, Int32 rowIndex, Int32 rowCount) at System.Windows.Forms.DataGridViewRowCollection.AddInternal(DataGridViewRow dataGridViewRow) at System.Windows.Forms.DataGridView.RefreshRows(Boolean scrollIntoView) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.ProcessListChanged(ListChangedEventArgs e) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object sender, ListChangedEventArgs e) at System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e) at System.Windows.Forms.CurrencyManager.List_ListChanged(Object sender, ListChangedEventArgs e) at System.Data.DataView.OnListChanged(ListChangedEventArgs e) at System.Data.DataView.UpdateIndex(Boolean force, Boolean fireEvent) at System.Data.DataView.UpdateIndex(Boolean force) at System.Data.DataView.SetIndex2(String newSort, DataViewRowState newRowStates, DataExpression newRowFilter, Boolean fireEvent) at System.Data.DataView.SetIndex(String newSort, DataViewRowState newRowStates, DataExpression newRowFilter) at System.Data.DataView.set_Sort(String value) at System.Data.DataView.System.ComponentModel.IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction) at System.Windows.Forms.DataGridView.SortInternal(IComparer comparer, DataGridViewColumn dataGridViewColumn, ListSortDirection direction) at System.Windows.Forms.DataGridView.Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction) at System.Windows.Forms.DataGridView.OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e) at System.Windows.Forms.DataGridView.OnMouseClick(MouseEventArgs e) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.DataGridView.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at GuardianConfig.Program.Main() in C:\vsswork\Guardian\GuardianConfig\GuardianConfig\GuardianConfig\Program.cs:line 18 at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()
| | malkie Monday, May 21, 2007 5:27 PM | I have experienced exactly the same problem. In my scenario, the AutoSizeColumnsMode is set to 'DisplayedCell'. When I click on a column header, I get a NullReferenceException. Stack trace is shown below.
Is this a bug in the DataGridView control? Does anyone know a workaround?
at System.Windows.Forms.DataGridView.ComputeVisibleColumns() at System.Windows.Forms.DataGridView.LayoutScrollBars() at System.Windows.Forms.DataGridView.ComputeLayout() at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean useRowShortcut, Boolean computeVisibleRows, Boolean invalidInAdjustFillingColumns, Boolean repositionEditingControl) at System.Windows.Forms.DataGridView.OnColumnWidthChanged(DataGridViewColumnEventArgs e) at System.Windows.Forms.DataGridView.OnBandThicknessChanged(DataGridViewBand dataGridViewBand) at System.Windows.Forms.DataGridView.AutoResizeColumnInternal(Int32 columnIndex, DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal, Boolean fixedHeight) at System.Windows.Forms.DataGridView.AutoResizeAllVisibleColumnsInternal(DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFilter, Boolean fixedHeight) at System.Windows.Forms.DataGridView.OnAddedRow_PostNotification(Int32 rowIndex) at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged_PostNotification(CollectionChangeAction cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow dataGridViewRow, Boolean changeIsDeletion, Boolean changeIsInsertion, Boolean recreateNewRow, Point newCurrentCell) at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged(CollectionChangeEventArgs e, Int32 rowIndex, Int32 rowCount) at System.Windows.Forms.DataGridViewRowCollection.AddInternal(DataGridViewRow dataGridViewRow) at System.Windows.Forms.DataGridView.RefreshRows(Boolean scrollIntoView) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.ProcessListChanged(ListChangedEventArgs e) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object sender, ListChangedEventArgs e) at System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e) at System.Windows.Forms.CurrencyManager.List_ListChanged(Object sender, ListChangedEventArgs e) at System.Windows.Forms.BindingSource.OnListChanged(ListChangedEventArgs e) at System.Windows.Forms.BindingSource.InnerList_ListChanged(Object sender, ListChangedEventArgs e) at System.Data.DataView.OnListChanged(ListChangedEventArgs e) at System.Data.DataView.UpdateIndex(Boolean force, Boolean fireEvent) at System.Data.DataView.UpdateIndex(Boolean force) at System.Data.DataView.SetIndex2(String newSort, DataViewRowState newRowStates, DataExpression newRowFilter, Boolean fireEvent) at System.Data.DataView.SetIndex(String newSort, DataViewRowState newRowStates, DataExpression newRowFilter) at System.Data.DataView.set_Sort(String value) at System.Data.DataView.System.ComponentModel.IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) at System.Windows.Forms.BindingSource.ApplySort(PropertyDescriptor property, ListSortDirection sort) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction) at System.Windows.Forms.DataGridView.SortInternal(IComparer comparer, DataGridViewColumn dataGridViewColumn, ListSortDirection direction) at System.Windows.Forms.DataGridView.Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction) at System.Windows.Forms.DataGridView.OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e) at System.Windows.Forms.DataGridView.OnMouseClick(MouseEventArgs e) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.DataGridView.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm)
| | Dave Wheeler Wednesday, August 29, 2007 2:29 PM | The same bug. I think I know conditions when it happens. If you somehow resize your last column to size bigger then size ofthe grid (for example column cell contains long string and user double click on columns delimiter to autoresize column) and then you change this long string to small, and then again double click on columns delimiter to autoresize this wide column, if newwidth will be small enough that more column then that wide column should became visible in grid -- then this exception is thrown.
Here is my stack trace:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Forms.DataGridView.ComputeVisibleColumns()
at System.Windows.Forms.DataGridView.LayoutScrollBars()
at System.Windows.Forms.DataGridView.ComputeLayout()
at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean useRowShortcut, Boolean computeVisibleRows, Boolean invalidInAdjustFillingColumns, Boolean repositionEditingControl)
at System.Windows.Forms.DataGridView.OnColumnWidthChanged(DataGridViewColumnEventArgs e)
at System.Windows.Forms.DataGridView.OnBandThicknessChanged(DataGridViewBand dataGridViewBand)
at System.Windows.Forms.DataGridView.AutoResizeColumnInternal(Int32 columnIndex, DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal, Boolean fixedHeight)
at System.Windows.Forms.DataGridView.OnColumnDividerDoubleClick(DataGridViewColumnDividerDoubleClickEventArgs e)
at System.Windows.Forms.DataGridView.OnMouseDoubleClick(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.DataGridView.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Here is .Net Framework 2.0 SP1, now I am sure  | | SergeyPV Wednesday, January 23, 2008 9:01 AM |
Sergey,
Istill believe this is a bug in the DataGridView control, which needs to be addressed by Microsoft. I recallthis being frustrating because I was unable to trap the exception using a try{] catch{} block.
However, I have since managed to prevent the exception occurring by changing the auto column resizing behaviour of my DataGridView control, as follows:-
In the designer view, right-click on the DataGridView control and select ‘Edit Columns� For each data bound column, I set Resizable = true and AutoSizeMode = NotSet. I want the last column to extend the full width of the form, so for this column only I set AutoSizeMode = Fill.
Inside my form_Load() method, I set the AutoResizeColumns and AllowUserToResizeColumns properties as shown below:-
this.dataGridView.AllowUserToResizeColumns = true; this.dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
This mode allows the user to resize the columns by dragging the column headers, or double-clicking to automatically size the column to the width of the widest visible cell.
I appreciate that this may not be the most desirable resizing behaviour for your application scenario, but a least it should prevent the System.NullReferenceException unhandled exception.
Please let me know if you find a better solution 
Dave | | Dave Wheeler Wednesday, January 23, 2008 11:23 AM | Dave Wheeler,
I agree that this is a bug in MS control and it isn't fixed in SP1. Thanks for workaround too, not fully fixes problem but anyway good!  | | SergeyPV Wednesday, January 23, 2008 3:54 PM | Guys, I am also facing the same problem. The problem occurs whe one cell is very large (contains a long string) and then i set it to a small string. The grid goes into one inconsistent state with only the row containing that cell as not resized. Then if i try to scroll it gives this exception. I am including the stack trace below.
System.NullReferenceException: Object reference not set to an instance of an object. at System.Windows.Forms.DataGridView.ComputeVisibleColumns() at System.Windows.Forms.DataGridView.set_HorizontalOffset(Int32 value) at System.Windows.Forms.DataGridView.DataGridViewHScrolled(Object sender, ScrollEventArgs se) at System.Windows.Forms.ScrollBar.OnScroll(ScrollEventArgs se) at System.Windows.Forms.ScrollBar.DoScroll(ScrollEventType type) at System.Windows.Forms.ScrollBar.WmReflectScroll(Message& m) at System.Windows.Forms.ScrollBar.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
I belive this is Microsoft bug. Can anyone suggest a work around for the same?
| | Manu Joseph Saturday, December 06, 2008 4:43 PM | Are you attempting to scroll the grid while it is being updated? For example, are you refreshing the grid contents on a timer event and clicking thescroll baratthe same time?Please provide more detail...
| | Dave Wheeler Monday, December 08, 2008 10:32 AM | No Dave, When the cell containing the large string is set with a small string the DataGridView attempts a resize. Then it goes into an inconsistent state as i mentioned above. If i close the grid then there is no problem. But if i try to scroll horizontally without scrolling the above exception is thrown.  | | Manu Joseph Tuesday, December 09, 2008 11:54 AM | I will try and explain this in steps so that i will not miss anything
1. Say the datagridview has 3 columns and the middle one is our culprit which can have these very long strings and very short strings
2. Add 3 rows to the DataGridView. In the first 2 rows let the middle column have 2 short strings (say of 10 characters each) and in the 3rd row the middle column should have a very long string (say 1000 characters). Now the size of the middle column is large due to the contents of the third row.
3. Now scroll to the right end. Now the only two columns visible should be the last 2
4. keeping this view set the contents of the middle column to empty string. (Do it programatically. Use a DataGridViewCustomButtonCell)
5. Observe that DataGridView attempts a resize and except the 3rd row all other rows are resized properly and the 3rd row is in a inconsistent state. And also the horizontal scrollbar is still there. Actually it should have disappeared.
6. Now attempt a horizontal scroll. See whether you are getting the same NullReferenceException.
PS: I have the screen shots for above steps. Is there anyway i can post it here?
Thanks a lot for your help!! | | Manu Joseph Tuesday, December 09, 2008 12:20 PM | Okay, your scenario is clearly different to mine. However, I think fundamentally we are experiencing the same bug. It is always a resize which puts the grid into an inconsistent state then a subsequent scrolling action which causes the exception.
In step 4 of your example, you could try disabling the grid auto-resize behaviour and manually performing a resize after changing your cell text. This will confirm that the issue is related to auto-resize.
Alternatively, you could download the debug symbols for System.Windows.Forms.DataGridView and try to step into the ComputeVisibleColumns() method using the debugger to find out what is causing the System.NullReferenceException.
I must admit that I am slightly surprised that nobody from Microsoft has offered any sort of response to this thread, given that it has now had over 1400 views and has been unresolved since May 2007.
| | Dave Wheeler Tuesday, December 09, 2008 12:49 PM | Thanks Dave, I have tried disabling the auto-resizing behaviour. The problem is not getting reproduced then. So the issue is related to auto-resize definitely. Auto-resize is a requirement for us. So cant disable that in the final output.  | | Manu Joseph Tuesday, December 09, 2008 2:27 PM | Yes, it looks like MS often is too concerned in doing something new and abandoning improving and properly maintaining old good things. Like why they still don't have nullable types in typed dataset, I don't know. | | SergeyPV Tuesday, December 09, 2008 2:35 PM |
That’s good. Now you know that it is definitely the grid auto-resizing that is causing your issue. I still maintain that the only way to tell for certain what it causing the System.NullReferenceException would be to debug into System.Windows.Forms.DataGridView::ComputeVisibleColumns(). If you have never debugged into .NET Framework source code before, I suggest you follow these guidelines http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx.
Auto-sizing is a requirement. In that case,as a workaround, would it bepossible to *temporarily* switch off the auto-sizing behaviour while you update the cell text? Or will the problem still occur the moment you switch it back on again? Alternatively, could you not simulate the auto-sizing behaviour by handling cell change events and manually coding the required grid resizing behaviour? | | Dave Wheeler Tuesday, December 09, 2008 2:58 PM | Yes!! Now it looks like i have to manually implement the cell resizing logic..
I will try debugging into .NET framework source code. I have not tried that before..
| | Manu Joseph Wednesday, December 10, 2008 5:18 AM | Hi
Thanks for the info in this thread! I hit this issue today with an application I had written - the grid in question had a column that returned a large text field. I limited the size of the text it could bring back and the problem went away. Not a permanent fix, but a good workaround for now.
Thanks, Mike. | | Michael Pitt Monday, February 23, 2009 10:05 PM | I am getting this nullreferenceexception with my datagridview as well.
It started throwing the exception when I clicked on row headers, now it also does it when I try and set readonly to True. If I set readonly = false it doesn't throw the exception.
I'm going to use the link above to debug further to see if mine is also related to this autosizing stuff. The suggestions above about autosizing did not fix my issue. | | Vegeta4ss Thursday, March 26, 2009 3:51 PM | Hello Friends,
I think, I can help you. I was having same issue before.! I was binding DataGrid with DataSource (Collection/DataSet). At that time If there is no data then, If you click on Headercell it was giving me same error of "Object Reference....". So,I use CurrencyManager to manage binding. So,If there is no record in datasource, then I set CurrencyManager.Position =-1. And it works fine.
SO, If you have same issue with datasource with 0 records. then try this one. It can help you.
Thank You
Best Regards Utkarsh Gajjar.
Utkarsh Gajjar | | Utkarsh Thursday, March 26, 2009 6:00 PM | Hi the issue is reported in https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366943as a bug, and is says it's closed and solved. I have added a comment there as I can't find the fix. Regards, MarianoC. | | MarianoC Friday, July 24, 2009 12:58 PM | MarianoC - many thanks for your post and sharing this information with us.
I've been waiting almost two years forthis fix, so please do let me (and the others subscribed to this thread) know when youdiscover whatthe fixis ;-)
In the meantime, Ihave managed to suppress the exception using the workaround which Idescribed in a post above. Unfortunately, this workarounddid not work for everyone, but it might be worth a try depending on your scenario.
Kind regards,
Dave | | Dave Wheeler Friday, July 24, 2009 1:18 PM |
|