Reputation: 138
I can work around this but would like to pin-point where and why this happens
as we all know NullReferenceException
is a .net exception indicating references made to an object before it has a value. But why would this happen if other properties can be assigned to the same object?
my example below:
'before this line, I create and populate a datatable (dt)
With dgvWMStockList
'assign the datasource to the dgv
.DataSource = dt
'configure its settings
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
.Columns("Description").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
'NullReferenceException gets thrown next
.Columns("Description").MinimumWidth = 200
End With
During debug, i get the error, then 1 second later, i can continue without editing the code. this indicates that the reference is either set from outside of the code or is set from another thread.
Note that moving the .MinimumWidth
call outside of the With
clause does not fix the problem.
The stack indicates:
at System.Windows.Forms.DataGridViewBand.set_Thickness(Int32 value)
at System.Windows.Forms.DataGridViewBand.set_MinimumThickness(Int32 value)
Anybody able to shed some light?
Upvotes: 0
Views: 287
Reputation: 1
A little bit late to the party, but maybe this can help someone who stumbles upon the same problem.
I had the same problem as OP and I think I figured out what happened.
As OP already pointed out, the NullPointerException only occurs in a tiny instant. Which makes it hard to debug, especially as you can't step into the code of the DAtaGridViewColumn. But what I gathered is, that it occurs when you set .Width
of a Column while .AutoSizeMode=DataGridViewAutoSizeColumnMode.Fill
.
In OPs case .Width
is set, because .MinimumWidth
is set to a value that is larger than the current value of .Width
, which tries to set .Width
to this value as well, which results in the Exception.
So the order of operations to avoid the exception should be:
.Columns("Description").Width = 200
.Columns("Description").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
.Columns("Description").MinimumWidth = 200
Upvotes: 0