dotnet / dotnet/winforms

Setting DataGridViewColumn.Visible may throw NullReferenceException

Open
#13,728 6 comments 0 reactions 1 assignee Claimed by @LeafShi1 View on GitHub
area-controls-DataGridView
Dominant language
C#
Stars
4.9k
Forks
1.1k
Avg merge
20h 23m
Merged PRs (30d)
103

Description

### .NET version

.NET 8.0 (Windows), target OS version 7.0

### Did it work in .NET Framework?

No

### Did it work in any of the earlier releases of .NET Core or .NET 5+?

_No response_

### Issue description

My app has a (subclassed) `DataGridView` that adds a right-click context menu, allowing the user to add and remove columns. So the user can right-click a column and choose "Hide This Column", and that `DataGridViewColumn` will be hidden by setting `Visible=false`.

The bug occurs if I have dragged the rightmost column to be very wide (much wider than the grid itself) so that only that rightmost column can be seen within the grid's scrollable bounds. I then right-click and choose to hide that column. The act of setting the `DataGridViewColumn`'s `Visible` property then unexpectedly throws `NullReferenceException` within Microsoft code:

```
System.NullReferenceException
HResult=0x80004003
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.OnColumnStateChanged(DataGridViewColumnStateChangedEventArgs e)
at System.Windows.Forms.DataGridView.OnDataGridViewElementStateChanged(DataGridViewElement element, Int32 index, DataGridViewElementStates elementState)
// this is where I set the Visible property
at Macrame.Ui.Grids.GridContextMenuBuilder.mnuHideCol_Click(Object sender, EventArgs e) in [REDACTED]\Ui\Grids\GridContextMenuBuilder.cs:line 125
```

### Steps to reproduce

See description above.

**Note:** I can reproduce this behaviour every time, in my large app, but I have not been able to reproduce it in a smaller test project. So please ask me if you need any further details about the state and properties at time of failure.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.