[RESOLVED] [2005] DataGridView Column Error
Hi Guys,
I've got this code which causes a Null Reference exception
Code:
If My.Computer.Keyboard.CtrlKeyDown Then
If e.KeyCode = Keys.P Then
If Me.DGJobLines.Columns("ClmLinePrice").Visible Then <---Here
Me.DGJobLines.Columns("ClmLinePrice").Visible = False
Else
Me.DGJobLines.Columns("ClmLinePrice").Visible = True
End If
End If
End If
If I use this code it works
Code:
If My.Computer.Keyboard.CtrlKeyDown Then
If e.KeyCode = Keys.P Then
If Me.DGJobLines.Columns(2).Visible Then
Me.DGJobLines.Columns(2).Visible = False
Else
Me.DGJobLines.Columns(2).Visible = True
End If
End If
End If
Here is how the column is added to the grid, and yes there are other columns as well.
Code:
Dim LinePriceCellStyle As New DataGridViewCellStyle
With LinePriceCellStyle
.Alignment = DataGridViewContentAlignment.MiddleRight
.Format = "c2"
.NullValue = "0.00"
End With
Dim ClmLinePrice As DataGridViewColumn = New DataGridViewTextBoxColumn
With ClmLinePrice
.Width = 50
.HeaderText = "Price"
.DefaultCellStyle = LinePriceCellStyle
.Visible = False
End With
Me.DGJobLines.Columns.Add(ClmLinePrice)
Any Ideas?
Fishy
Re: [2005] DataGridView Column Error
Code:
If My.Computer.Keyboard.CtrlKeyDown Then
If e.KeyCode = Keys.P Then
If Me.DGJobLines.Columns("ClmLinePrice").Visible Then <---Here
Me.DGJobLines.Columns("ClmLinePrice").Visible = False
Else
Me.DGJobLines.Columns("ClmLinePrice").Visible = True
End If
End If
End If
ClmLinePrice is the name of your column in memory, but not in the actual DataGridView. Try changing to this:
Code:
If My.Computer.Keyboard.CtrlKeyDown Then
If e.KeyCode = Keys.P Then
If Me.DGJobLines.Columns("Price").Visible Then <---Here
Me.DGJobLines.Columns("Price").Visible = False
Else
Me.DGJobLines.Columns("Price").Visible = True
End If
End If
End If
Re: [2005] DataGridView Column Error
The HeaderText is irrelevant. This:
vb.net Code:
If Me.DGJobLines.Columns("ClmLinePrice").Visible Then
is trying to use a column whose Name is "ClmLinePrice". This:
vb.net Code:
Dim ClmLinePrice As DataGridViewColumn = New DataGridViewTextBoxColumn
With ClmLinePrice
.Width = 50
.HeaderText = "Price"
.DefaultCellStyle = LinePriceCellStyle
.Visible = False
End With
Me.DGJobLines.Columns.Add(ClmLinePrice)
is adding a column with no Name at all. If you want the Name to be "ClmLinePrice" then you have to set the Name to "ClmLinePrice":
Code:
Dim ClmLinePrice As DataGridViewColumn = New DataGridViewTextBoxColumn
With ClmLinePrice
.Name = "ClmLinePrice"
.Width = 50
.HeaderText = "Price"
.DefaultCellStyle = LinePriceCellStyle
.Visible = False
End With
Me.DGJobLines.Columns.Add(ClmLinePrice)
Re: [2005] DataGridView Column Error
Nice catch. I overlooked HeaderText while skimming for parenthesis.
Re: [2005] DataGridView Column Error
Thanks jm, Could not see the wood for the trees then.